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 14 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,11 @@ 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 = s_meter.CreateObservableCounter(
"dotnet.process.cpu.time",
GetCpuTime,
unit: "s",
description: "CPU time used by the process as reported by the CLR.");
tarekgh marked this conversation as resolved.
Show resolved Hide resolved

public static bool IsEnabled()
{
Expand All @@ -172,8 +171,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;
}

private static IEnumerable<Measurement<long>> GetGarbageCollectionCounts()
Expand All @@ -188,17 +187,16 @@ 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()
{
if (OperatingSystem.IsBrowser() || OperatingSystem.IsTvOS() || OperatingSystem.IsIOS())
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
yield break;

// 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
54 changes: 27 additions & 27 deletions src/libraries/System.Private.CoreLib/src/Resources/Strings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema

Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple

There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down
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.IO;
using System.Runtime.Versioning;
tarekgh marked this conversation as resolved.
Show resolved Hide resolved

namespace System
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
tarekgh marked this conversation as resolved.
Show resolved Hide resolved

namespace System
{
Expand Down
Loading
Loading