Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ClrThreadPool.CpuUtilizationReader.Windows.cs « Threading « System « src « System.Private.CoreLib « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 915f111063bd6f84384d73aee1544baa14d86488 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics;
using System.Runtime.InteropServices;

namespace System.Threading
{
    internal partial class ClrThreadPool
    {
        private class CpuUtilizationReader
        {
            private struct ProcessCpuInformation
            {
                public long idleTime;
                public long kernelTime;
                public long userTime;
            }

            private ProcessCpuInformation _processCpuInfo = new ProcessCpuInformation();

            public int CurrentUtilization
            {
                get
                {
                    if (!Interop.Kernel32.GetSystemTimes(out var idleTime, out var kernelTime, out var userTime))
                    {
                        int error = Marshal.GetLastWin32Error();
                        var exception = new OutOfMemoryException();
                        exception.HResult = error;
                        throw exception;
                    }

                    long cpuTotalTime = ((long)userTime - _processCpuInfo.userTime) + ((long)kernelTime - _processCpuInfo.kernelTime);
                    long cpuBusyTime = cpuTotalTime - ((long)idleTime - _processCpuInfo.idleTime);

                    _processCpuInfo.kernelTime = (long)kernelTime;
                    _processCpuInfo.userTime = (long)userTime;
                    _processCpuInfo.idleTime = (long)idleTime;

                    if (cpuTotalTime > 0 && cpuBusyTime > 0)
                    {
                        long reading = cpuBusyTime * 100 / cpuTotalTime;
                        reading = Math.Min(reading, 100);
                        Debug.Assert(0 <= reading);
                        return (int)reading;
                    }
                    return 0;
                }
            }
        }
    }
}