Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introducing Environment.CpuUsage #105152

Merged
merged 24 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,14 @@ static RuntimeMetrics()
unit: "{cpu}",
description: "The number of processors available to the process.");

// TODO - Uncomment once an implementation for https://github.com/dotnet/runtime/issues/104844 is available.
//private static readonly ObservableCounter<double> s_processCpuTime = s_meter.CreateObservableCounter(
// "dotnet.process.cpu.time",
// GetCpuTime,
// unit: "s",
// description: "CPU time used by the process as reported by the CLR.");
private static readonly ObservableCounter<double>? s_processCpuTime =
OperatingSystem.IsBrowser() || OperatingSystem.IsTvOS() || (OperatingSystem.IsIOS() && !OperatingSystem.IsMacCatalyst()) ?
null :
s_meter.CreateObservableCounter(
"dotnet.process.cpu.time",
GetCpuTime,
unit: "s",
description: "CPU time used by the process.");

public static bool IsEnabled()
{
Expand All @@ -172,8 +174,8 @@ public static bool IsEnabled()
|| s_threadPoolQueueLength.Enabled
|| s_assembliesCount.Enabled
|| s_exceptions.Enabled
|| s_processCpuCount.Enabled;
//|| s_processCpuTime.Enabled;
|| s_processCpuCount.Enabled
|| (s_processCpuTime is not null && s_processCpuTime.Enabled);
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
}

private static IEnumerable<Measurement<long>> GetGarbageCollectionCounts()
Expand All @@ -188,17 +190,18 @@ private static IEnumerable<Measurement<long>> GetGarbageCollectionCounts()
}
}

// TODO - Uncomment once an implementation for https://github.com/dotnet/runtime/issues/104844 is available.
//private static IEnumerable<Measurement<double>> GetCpuTime()
//{
// if (OperatingSystem.IsBrowser() || OperatingSystem.IsTvOS() || OperatingSystem.IsIOS())
// yield break;
private static IEnumerable<Measurement<double>> GetCpuTime()
{
Debug.Assert(s_processCpuTime is not null);
Debug.Assert(!OperatingSystem.IsBrowser() && !OperatingSystem.IsTvOS() && !(OperatingSystem.IsIOS() && !OperatingSystem.IsMacCatalyst()));

// ProcessCpuUsage processCpuUsage = Environment.CpuUsage;
#pragma warning disable CA1416 // This call site is reachable on all platforms. 'Environment.CpuUsage' is unsupported on: 'ios', 'tvos'
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
Environment.ProcessCpuUsage processCpuUsage = Environment.CpuUsage;
#pragma warning restore CA1416

// yield return new(processCpuUsage.UserTime.TotalSeconds, [new KeyValuePair<string, object?>("cpu.mode", "user")]);
// yield return new(processCpuUsage.PrivilegedTime.TotalSeconds, [new KeyValuePair<string, object?>("cpu.mode", "system")]);
//}
yield return new(processCpuUsage.UserTime.TotalSeconds, [new KeyValuePair<string, object?>("cpu.mode", "user")]);
yield return new(processCpuUsage.PrivilegedTime.TotalSeconds, [new KeyValuePair<string, object?>("cpu.mode", "system")]);
}

private static IEnumerable<Measurement<long>> GetHeapSizes()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,48 +112,47 @@ public void GcCollectionsCount()
}
}

// TODO - Uncomment once an implementation for https://github.com/dotnet/runtime/issues/104844 is available.
//[Fact]
//public void CpuTime()
//{
// using InstrumentRecorder<double> instrumentRecorder = new("dotnet.process.cpu.time");

// instrumentRecorder.RecordObservableInstruments();

// bool[] foundCpuModes = [false, false];

// foreach (Measurement<double> measurement in instrumentRecorder.GetMeasurements().Where(m => m.Value >= 0))
// {
// var tags = measurement.Tags.ToArray();
// var tag = tags.SingleOrDefault(k => k.Key == "cpu.mode");

// if (tag.Key is not null)
// {
// Assert.True(tag.Value is string, "Expected CPU mode tag to be a string.");

// string tagValue = (string)tag.Value;

// switch (tagValue)
// {
// case "user":
// foundCpuModes[0] = true;
// break;
// case "system":
// foundCpuModes[1] = true;
// break;
// default:
// Assert.Fail($"Unexpected CPU mode tag value '{tagValue}'.");
// break;
// }
// }
// }

// for (int i = 0; i < foundCpuModes.Length; i++)
// {
// var mode = i == 0 ? "user" : "system";
// Assert.True(foundCpuModes[i], $"Expected to find a measurement for '{mode}' CPU mode.");
// }
//}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
public void CpuTime()
{
using InstrumentRecorder<double> instrumentRecorder = new("dotnet.process.cpu.time");

instrumentRecorder.RecordObservableInstruments();

bool[] foundCpuModes = [false, false];

foreach (Measurement<double> measurement in instrumentRecorder.GetMeasurements().Where(m => m.Value >= 0))
{
var tags = measurement.Tags.ToArray();
var tag = tags.SingleOrDefault(k => k.Key == "cpu.mode");

if (tag.Key is not null)
{
Assert.True(tag.Value is string, "Expected CPU mode tag to be a string.");

string tagValue = (string)tag.Value;

switch (tagValue)
{
case "user":
foundCpuModes[0] = true;
break;
case "system":
foundCpuModes[1] = true;
break;
default:
Assert.Fail($"Unexpected CPU mode tag value '{tagValue}'.");
break;
}
}
}

for (int i = 0; i < foundCpuModes.Length; i++)
{
var mode = i == 0 ? "user" : "system";
Assert.True(foundCpuModes[i], $"Expected to find a measurement for '{mode}' CPU mode.");
}
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
public void ExceptionsCount()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ public TimeSpan TotalProcessorTime
{
get
{
if (IsCurrentProcess)
{
return Environment.CpuUsage.TotalTime;
}

EnsureState(State.HaveNonExitedId);
Interop.Process.proc_stats stat = Interop.Process.GetThreadInfo(_processId, 0);
return Process.TicksToTimeSpan(stat.userTime + stat.systemTime);
Expand All @@ -51,6 +56,11 @@ public TimeSpan UserProcessorTime
{
get
{
if (IsCurrentProcess)
{
return Environment.CpuUsage.UserTime;
}

EnsureState(State.HaveNonExitedId);

Interop.Process.proc_stats stat = Interop.Process.GetThreadInfo(_processId, 0);
Expand All @@ -66,6 +76,11 @@ public TimeSpan PrivilegedProcessorTime
{
get
{
if (IsCurrentProcess)
{
return Environment.CpuUsage.PrivilegedTime;
}

EnsureState(State.HaveNonExitedId);

Interop.Process.proc_stats stat = Interop.Process.GetThreadInfo(_processId, 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ public static Process[] GetProcessesByName(string? processName, string machineNa
[SupportedOSPlatform("maccatalyst")]
public TimeSpan PrivilegedProcessorTime
{
get
{
return TicksToTimeSpan(GetStat().stime);
}
get => IsCurrentProcess ? Environment.CpuUsage.PrivilegedTime : TicksToTimeSpan(GetStat().stime);
}

/// <summary>Gets the time the associated process was started.</summary>
Expand Down Expand Up @@ -132,6 +129,11 @@ public TimeSpan TotalProcessorTime
{
get
{
if (IsCurrentProcess)
{
return Environment.CpuUsage.TotalTime;
}

Interop.procfs.ParsedStat stat = GetStat();
return TicksToTimeSpan(stat.utime + stat.stime);
}
Expand All @@ -146,10 +148,7 @@ public TimeSpan TotalProcessorTime
[SupportedOSPlatform("maccatalyst")]
public TimeSpan UserProcessorTime
{
get
{
return TicksToTimeSpan(GetStat().utime);
}
get => IsCurrentProcess ? Environment.CpuUsage.UserTime : TicksToTimeSpan(GetStat().utime);
}

partial void EnsureHandleCountPopulated()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ public TimeSpan PrivilegedProcessorTime
{
get
{
if (IsCurrentProcess)
{
return Environment.CpuUsage.PrivilegedTime;
}

EnsureState(State.HaveNonExitedId);
Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId);
return MapTime(info.ri_system_time);
Expand Down Expand Up @@ -64,6 +69,11 @@ public TimeSpan TotalProcessorTime
{
get
{
if (IsCurrentProcess)
{
return Environment.CpuUsage.TotalTime;
}

EnsureState(State.HaveNonExitedId);
Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId);
return MapTime(info.ri_system_time + info.ri_user_time);
Expand All @@ -81,6 +91,11 @@ public TimeSpan UserProcessorTime
{
get
{
if (IsCurrentProcess)
{
return Environment.CpuUsage.UserTime;
}

EnsureState(State.HaveNonExitedId);
Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId);
return MapTime(info.ri_user_time);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ private DateTime ExitTimeCore
[SupportedOSPlatform("maccatalyst")]
public TimeSpan PrivilegedProcessorTime
{
get { return GetProcessTimes().PrivilegedProcessorTime; }
get => IsCurrentProcess ? Environment.CpuUsage.PrivilegedTime : GetProcessTimes().PrivilegedProcessorTime;
}

/// <summary>Gets the time the associated process was started.</summary>
Expand All @@ -251,7 +251,7 @@ internal DateTime StartTimeCore
[SupportedOSPlatform("maccatalyst")]
public TimeSpan TotalProcessorTime
{
get { return GetProcessTimes().TotalProcessorTime; }
get => IsCurrentProcess ? Environment.CpuUsage.TotalTime : GetProcessTimes().TotalProcessorTime;
}

/// <summary>
Expand All @@ -263,7 +263,7 @@ public TimeSpan TotalProcessorTime
[SupportedOSPlatform("maccatalyst")]
public TimeSpan UserProcessorTime
{
get { return GetProcessTimes().UserProcessorTime; }
get => IsCurrentProcess ? Environment.CpuUsage.UserTime : GetProcessTimes().UserProcessorTime;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,8 @@ public static Process[] GetProcesses(string machineName)
return processes;
}

private bool IsCurrentProcess => _processId == Environment.ProcessId;

/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;

Expand Down Expand Up @@ -69,5 +70,36 @@ private static int CheckedSysConf(Interop.Sys.SysConfName name)
}
return (int)result;
}

/// <summary>
/// Get the CPU usage, including the process time spent running the application code, the process time spent running the operating system code,
/// and the total time spent running both the application and operating system code.
/// </summary>
[SupportedOSPlatform("maccatalyst")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
[UnsupportedOSPlatform("browser")]
public static ProcessCpuUsage CpuUsage
{
get
{
Interop.Sys.ProcessCpuInformation cpuInfo = default;
Interop.Sys.GetCpuUtilization(ref cpuInfo);

ulong userTime100Nanoseconds = cpuInfo.lastRecordedUserTime / 100; // nanoseconds to 100-nanoseconds
if (userTime100Nanoseconds > long.MaxValue)
{
userTime100Nanoseconds = long.MaxValue;
}
tarekgh marked this conversation as resolved.
Show resolved Hide resolved

ulong kernelTime100Nanoseconds = cpuInfo.lastRecordedKernelTime / 100; // nanoseconds to 100-nanoseconds
if (kernelTime100Nanoseconds > long.MaxValue)
{
kernelTime100Nanoseconds = long.MaxValue;
}

return new ProcessCpuUsage { UserTime = new TimeSpan((long)userTime100Nanoseconds), PrivilegedTime = new TimeSpan((long)kernelTime100Nanoseconds) };
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Microsoft.Win32.SafeHandles;

Expand Down Expand Up @@ -358,5 +359,20 @@ private static unsafe string[] SegmentCommandLine(char* cmdLine)

return arrayBuilder.ToArray();
}

/// <summary>
/// Get the CPU usage, including the process time spent running the application code, the process time spent running the operating system code,
/// and the total time spent running both the application and operating system code.
/// </summary>
[SupportedOSPlatform("maccatalyst")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
[UnsupportedOSPlatform("browser")]
public static ProcessCpuUsage CpuUsage
{
get => Interop.Kernel32.GetProcessTimes(Interop.Kernel32.GetCurrentProcess(), out _, out _, out long procKernelTime, out long procUserTime) ?
new ProcessCpuUsage { UserTime = new TimeSpan(procUserTime), PrivilegedTime = new TimeSpan(procKernelTime) } :
new ProcessCpuUsage { UserTime = TimeSpan.Zero, PrivilegedTime = TimeSpan.Zero };
}
}
}
25 changes: 25 additions & 0 deletions src/libraries/System.Private.CoreLib/src/System/Environment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,31 @@ namespace System
{
public static partial class Environment
{
/// <summary>
/// Represents the CPU usage statistics of a process.
/// </summary>
/// <remarks>
/// The CPU usage statistics include information about the time spent by the process in the application code (user mode) and the operating system code (kernel mode),
/// as well as the total time spent by the process in both user mode and kernel mode.
/// </remarks>
public readonly struct ProcessCpuUsage
{
/// <summary>
/// Gets the amount of time the associated process has spent running code inside the application portion of the process (not the operating system code).
/// </summary>
public TimeSpan UserTime { get; internal init; }

/// <summary>
/// Gets the amount of time the process has spent running code inside the operating system code.
/// </summary>
public TimeSpan PrivilegedTime { get; internal init; }

/// <summary>
/// Gets the amount of time the process has spent utilizing the CPU including the process time spent in the application code and the process time spent in the operating system code.
/// </summary>
public TimeSpan TotalTime => UserTime + PrivilegedTime;
}

public static int ProcessorCount { get; } = GetProcessorCount();

/// <summary>
Expand Down
Loading
Loading