C#计算指定进程占用CPU的使用率(窗口用Timer刷新1s1次)求指点,算的跟实际任务管理器差距极大
   private void getCPUDeatil(Process cur)
    {
        //listView1.Items.Clear();
        var item1 = new ListViewItem();
        //item1.ImageIndex = 1;
        //获取当前进程对象
        //Process cur = Process.GetCurrentProcess();
        //行中添加进程名 
        item1.Text = cur.ProcessName;
        //Console.WriteLine(curtime.NextValue());
        PerformanceCounter curpcp = new PerformanceCounter("Process", "Working Set - Private", cur.ProcessName);
        PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName);
        PerformanceCounter curtime = new PerformanceCounter("Process", "% Processor Time", cur.ProcessName);
        PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
        //上次记录CPU的时间
        TimeSpan prevCpuTime = TimeSpan.Zero;
        curtime.NextValue();
        //Sleep的时间间隔
        double interval = timer1.Interval;

        PerformanceCounter totalcpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");

        //当前时间
        TimeSpan curCpuTime = cur.TotalProcessorTime;
        //计算
        double value = (curCpuTime - prevCpuTime).TotalMilliseconds /interval/ Environment.ProcessorCount * 10;
        prevCpuTime = curCpuTime;
        //将值加入窗口
        item1.SubItems.Add(Math.Round(curpcp.NextValue() / 1024/1024, 2) + "MB");
        item1.SubItems.Add(Math.Round(curtime.NextValue()/Environment.ProcessorCount, 2) + "%");
        //item1.SubItems.Add(Math.Round(value, 2) + "%");
        item1.SubItems.Add(Convert.ToString(cur.Id));
        listView1.Items.Add(item1);

    }
private void timer2_Tick(object sender, EventArgs e)
        {
            listView1.Items.Clear();

            Process pro1;
            pro1 = Process.GetCurrentProcess();
            getCPUDeatil(pro1);
            Process[] pro2 = Process.GetProcessesByName("CefSharp.BrowserSubprocess");
            //curtime.InstanceName = "CefSharp.BrowserSubprocess";
            for (int i = 0; i < pro2.Length; i++)
            {
                //curtime = new PerformanceCounter("Process", "% Processor Time",pro2[i].ProcessName);
                //Console.WriteLine(curtime.InstanceName);
                getCPUDeatil(pro2[i]);
            }
        }

这是我写的代码,不太规范,也是到处复制的,计算的跟实际的任务管理器的相差太大,上面要求用timer刷新,timer每次刷新,里面的代码都要重新加载一次可能导致计算差距大。求大神指点啊,急急急!!!

1个回答

% Processor Time算的是相对一个cpu的占比,如果你是多核心cpu,这个值需要除以计算机上的逻辑cpu的个数。(你在任务管理器看到几个框就除以几)

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问