Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mono / utils / mono-proclib-windows.c
1 /**
2  * \file
3  * Windows proclib support for Mono.
4  *
5  * Copyright 2016 Microsoft
6  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
7 */
8
9 #include <config.h>
10 #include <glib.h>
11
12 #ifdef HOST_WIN32
13 #include <windows.h>
14 #include "mono/utils/mono-proclib.h"
15
16 int
17 mono_process_current_pid ()
18 {
19         return (int) GetCurrentProcessId ();
20 }
21
22 /**
23  * mono_cpu_count:
24  * \returns the number of processors on the system.
25  */
26 int
27 mono_cpu_count (void)
28 {
29         SYSTEM_INFO info;
30         GetSystemInfo (&info);
31         return info.dwNumberOfProcessors;
32 }
33
34 /*
35  * This function returns the cpu usage in percentage,
36  * normalized on the number of cores.
37  *
38  * Warning : the percentage returned can be > 100%. This
39  * might happens on systems like Android which, for
40  * battery and performance reasons, shut down cores and
41  * lie about the number of active cores.
42  */
43 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
44 gint32
45 mono_cpu_usage (MonoCpuUsageState *prev)
46 {
47         gint32 cpu_usage = 0;
48         gint64 cpu_total_time;
49         gint64 cpu_busy_time;
50         guint64 idle_time;
51         guint64 kernel_time;
52         guint64 user_time;
53
54         if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
55                 g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
56                 return -1;
57         }
58
59         cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
60         cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
61
62         if (prev) {
63                 prev->idle_time = idle_time;
64                 prev->kernel_time = kernel_time;
65                 prev->user_time = user_time;
66         }
67
68         if (cpu_total_time > 0 && cpu_busy_time > 0)
69                 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
70
71         return cpu_usage;
72 }
73 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
74 #endif /* HOST_WIN32*/