Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ namespace System.Diagnostics
{
public partial class Process
{
private const int NanoSecondsTo100NanosecondsFactor = 100;
Comment thread
gregkalapos marked this conversation as resolved.

/// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary>
public TimeSpan PrivilegedProcessorTime
{
get
{
EnsureState(State.HaveNonExitedId);
Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId);
return new TimeSpan(Convert.ToInt64(info.ri_system_time));
return new TimeSpan(Convert.ToInt64(info.ri_system_time / NanoSecondsTo100NanosecondsFactor));
}
}

Expand Down Expand Up @@ -76,7 +78,7 @@ public TimeSpan TotalProcessorTime
{
EnsureState(State.HaveNonExitedId);
Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId);
return new TimeSpan(Convert.ToInt64(info.ri_system_time + info.ri_user_time));
return new TimeSpan(Convert.ToInt64((info.ri_system_time + info.ri_user_time) / NanoSecondsTo100NanosecondsFactor));
}
}

Expand All @@ -90,7 +92,7 @@ public TimeSpan UserProcessorTime
{
EnsureState(State.HaveNonExitedId);
Interop.libproc.rusage_info_v3 info = Interop.libproc.proc_pid_rusage(_processId);
return new TimeSpan(Convert.ToInt64(info.ri_user_time));
return new TimeSpan(Convert.ToInt64(info.ri_user_time / NanoSecondsTo100NanosecondsFactor));
}
}

Expand Down
27 changes: 27 additions & 0 deletions src/System.Diagnostics.Process/tests/ProcessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,33 @@ public void TestProcessorTime()
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}

[Fact]
[ActiveIssue(31908, TargetFrameworkMonikers.Uap)]
public void TotalProcessorTime_PerformLoop_TotalProcessorTimeValid()
{
CreateDefaultProcess();

DateTime startTime = DateTime.UtcNow;
TimeSpan processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime;

// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
}

TimeSpan processorTimeAfterSpin = Process.GetCurrentProcess().TotalProcessorTime;
Comment thread
stephentoub marked this conversation as resolved.
DateTime endTime = DateTime.UtcNow;

double timeDiff = (endTime - startTime).TotalMilliseconds;
double cpuTimeDiff = (processorTimeAfterSpin - processorTimeBeforeSpin).TotalMilliseconds;

double cpuUsage = cpuTimeDiff / (timeDiff * Environment.ProcessorCount);

Assert.InRange(cpuUsage, 0, 1);
}

[Fact]
public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
Expand Down