【问题标题】:Get the realtime CPU speed in C#?在 C# 中获取实时 CPU 速度?
【发布时间】:2020-06-08 16:36:11
【问题描述】:

The existing question 建议CurrentClockSpeed,但在我的系统中,它只返回与MaxClockSpeed 相同的值。下面的代码一遍又一遍地打印出相同的两个值。

        Task.Run(() =>
        {
            ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
            while (true)
            {
                Debug.WriteLine("Max=" + Mo["MaxClockSpeed"] + ", Current=" + Mo["CurrentClockSpeed"]);
                System.Threading.Thread.Sleep(1000);
            }
            Mo.Dispose(); //return and such later in the code
        });

但所有其他应用程序,如任务管理器、CPU-Z、硬件信息等,都显示可变时钟速度。也就是说,如果我运行一个使用 100% CPU 的进程,速度就会提高,如果我终止该进程,它就会下降。我怎样才能得到那个值?

我的意思是,例如,我在 Google 搜索中找到的屏幕截图的“速度”部分中的值。不是永远不变的“最大速度”值。

【问题讨论】:

  • 你看过this的相关帖子吗?
  • @AxelKemper 也许就是这样。似乎cpuCounter.NextValue() 正在返回基本时钟速度的百分比。当我测试它时,它从大约 100 变为大约 110。

标签: c# windows cpu-usage


【解决方案1】:

如果您的意思是 CPU 当前使用进程 在单独的线程中使用这个函数:

private void get_cpuUsage()
        {
            try
            {
                string processname = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
                var perfCounter = new PerformanceCounter("Process", "% Processor Time", processname);

                int coreCount = 0;
                foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
                {
                    coreCount += int.Parse(item["NumberOfCores"].ToString());
                }

                while (true)
                {
                    Thread.Sleep(500);
                    double perfVal = perfCounter.NextValue() / Environment.ProcessorCount;
                    int cpu = (int)Math.Round(perfVal, 0);// / 
                    double cpuvalue = Math.Round(perfVal, 1);
                    Invoke((MethodInvoker)delegate
                    {

                        cpu_bar.Text = cpuvalue.ToString(); // diaplay current % processes 
                    });
                }
            }
            catch(Exception ex)
            {
messagebox.show(ex.message);

            }
        }

【讨论】:

  • 不,不是 CPU 利用率,而是 CPU 时钟速度。我不知道你为什么会这样,但如果那是因为 CPU 使用率图表上的红色箭头,我从谷歌图片搜索中找到了这张图片,正如我所指出的,所以不是我放了那个红色箭头,我是对 CPU 使用率不感兴趣。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多