计算当前进程的CPU百分比

本文关键字:CPU 百分比 进程 计算 | 更新日期: 2023-09-27 18:28:33

我使用以下代码来计算进程的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%),与其他流程也有这种差异。

造成这种差异的原因是什么?

计算当前进程的CPU百分比

除了同意Damien的观点,即你试图做的事情似乎真的没有意义之外,你会得到与预期不同的值还有很多原因。

  1. CCD_ 1。这里已经回答了这个问题:C#日期时间。现在是精度。总之,DateTime并非用于精确测量,它只是表示当前日期和时间
  2. CCD_ 3。这里提到:我们如何降低myProcess.TotalProcessorTime的分辨率?。总之,这是基于时钟中断频率的,默认情况下,时钟中断频率为每秒64次