我正在使用此代码计算进程的cpu使用情况:
using System;
using System.Timers;
public partial class Service1 : ServiceBase
{
System.Timers.Timer CpuTimer = new System.Timers.Timer();
public static TimeSpan LastCpuTime;
public static DateTime LastCpuTimeChecked;
protected override void OnStart(string[] args)
{
// Set up a timer to check the CPU every second or whatever.
CpuTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
CpuTimer.Interval = 1000;
CpuTimer.Enabled = true;
}
private static void OnTimedEvent(object Source, ElapsedEventArgs e)
{
// Get the
Int16 CpuPercentage = GetCpuPercentage(System.Diagnostics.Process.GetCurrentProcess());
}
private static Int16 GetCpuPercentage(System.Diagnostics.Process Process)
{
if (LastCpuTime == null)
{
// For the first run-through, we just need to start the clock.
LastCpuTime = Process.TotalProcessorTime;
LastCpuTimeChecked = DateTime.Now;
}
else
{
// How long since the last check?
TimeSpan TimeElapsed = DateTime.Now - LastCpuTimeChecked;
// How much CPU time was used?
TimeSpan CpuTimePerProc = (Process.TotalProcessorTime - LastCpuTime);
// Reset the clocks.
LastCpuTime = Process.TotalProcessorTime;
LastCpuTimeChecked = DateTime.Now;
// Calculate the percentage of CPU time used by this process.
Int16 CpuPercentage = (Int16)(
(float)CpuTimePerProc.TotalMilliseconds /
(float)TimeElapsed.TotalMilliseconds /
Environment.ProcessorCount * 100
);
return CpuPercentage;
}
// Return something if we don't yet have enough data.
return 0;
}
}
但结果与任务管理器有很大差异(2-3%)。这也与其他流程有所不同。
造成这种差异的原因是什么?
答案 0 :(得分:1)
除了同意达米恩之外,你正在尝试做的事情似乎并没有多大意义,因此有很多理由可以让你获得与预期不同的价值。
DateTime
的准确性。这已在这里得到解答:C# DateTime.Now precision。总而言之,DateTime
并非用于精确测量 - 它仅用于表示当前日期和时间。Processor.TotalProcessorTime
的准确性。这在这里提到:How we can reduce the resolution of myProcess.TotalProcessorTime?。总而言之,这是基于时钟中断频率,默认情况下每秒钟频率为64次。