Build mono runtime under none desktop Windows API family, adjustments and cleanup.
[mono.git] / mono / utils / mono-proclib-windows-uwp.c
1 /*
2  * mono-proclib-windows-uwp.c: UWP proclib support for Mono.
3  *
4  * Copyright 2016 Microsoft
5  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
6 */
7 #include <config.h>
8 #include <glib.h>
9 #include "mono/utils/mono-compiler.h"
10
11 #if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
12 #include <windows.h>
13 #include <mono/utils/mono-proclib.h>
14
15 gint32
16 mono_cpu_usage (MonoCpuUsageState *prev)
17 {
18         gint32 cpu_usage = 0;
19         gint64 cpu_total_time;
20         gint64 cpu_busy_time;
21         guint64 idle_time;
22         guint64 kernel_time;
23         guint64 user_time;
24         guint64 current_time;
25         guint64 creation_time;
26         guint64 exit_time;
27
28         GetSystemTimeAsFileTime ((FILETIME*)&current_time);
29         if (!GetProcessTimes (GetCurrentProcess (), (FILETIME*)&creation_time, (FILETIME*)&exit_time, (FILETIME*)&kernel_time, (FILETIME*)&user_time)) {
30                 g_error ("GetProcessTimes() failed, error code is %d\n", GetLastError ());
31                 return -1;
32         }
33
34         // GetProcessTimes user_time is a sum of user time spend by all threads in the process.
35         // This means that the total user time can be more than real time. In order to adjust for this
36         // the total available time that we can be scheduled depends on the number of available cores.
37         // For example, having 2 threads running 100% on a 2 core system for 100 ms will return a user_time of 200ms
38         // but the current_time - creation_time will only be 100ms but by adjusting the available time based on number of
39         // of availalbe cores will gives use the total load of the process.
40         guint64 total_available_time = (current_time - creation_time) * mono_cpu_count ();
41
42         idle_time = total_available_time - (kernel_time + user_time);
43
44         cpu_total_time = (gint64)((idle_time - (prev ? prev->idle_time : 0)) + (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
45         cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
46
47         if (prev) {
48                 prev->idle_time = idle_time;
49                 prev->kernel_time = kernel_time;
50                 prev->user_time = user_time;
51         }
52
53         if (cpu_total_time > 0 && cpu_busy_time > 0)
54                 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
55
56         return cpu_usage;
57 }
58
59 #else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
60
61 MONO_EMPTY_SOURCE_FILE (mono_proclib_windows_uwp);
62 #endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */