Skip to content

Commit

Permalink
Introducing Environment.CpuUsage (dotnet#105152)
Browse files Browse the repository at this point in the history
* Introducing Environment.CpuUsage

* Check Unix builds

* increment

* update 1

* enable browser test

* revert to use init.

* Updates

* Fix OSX build failures

* Fix MACCATALYST builds

* Address different feedback

* Addressing more feedback

* cleanup

* revert the resources file change

* addressing the feedback

* Update the test

* kittle tweaks

* ref fix

* minore comment fix.

* revert un-intended change

* Fix the test with with the browser

* simplify some code
  • Loading branch information
tarekgh committed Jul 21, 2024
1 parent d285c82 commit 7069cb3
Show file tree
Hide file tree
Showing 12 changed files with 220 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading;

namespace System.Diagnostics.Metrics
Expand Down Expand Up @@ -146,12 +147,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 +175,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?.Enabled is true;
}

private static IEnumerable<Measurement<long>> GetGarbageCollectionCounts()
Expand All @@ -188,17 +191,20 @@ 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;
[SupportedOSPlatform("maccatalyst")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
[UnsupportedOSPlatform("browser")]
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;
Environment.ProcessCpuUsage processCpuUsage = Environment.CpuUsage;

// 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,28 @@ 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")]
[UnsupportedOSPlatform("browser")]
public static ProcessCpuUsage CpuUsage
{
get
{
Interop.Sys.ProcessCpuInformation cpuInfo = default;
Interop.Sys.GetCpuUtilization(ref cpuInfo);

// Division by 100 is to convert the nanoseconds to 100-nanoseconds to match .NET time units (100-nanoseconds).
ulong userTime100Nanoseconds = Math.Min(cpuInfo.lastRecordedUserTime / 100, (ulong)long.MaxValue);
ulong kernelTime100Nanoseconds = Math.Min(cpuInfo.lastRecordedKernelTime / 100, (ulong)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 };
}
}
}
Loading

0 comments on commit 7069cb3

Please sign in to comment.