【问题标题】:Keeping CPU Usage Low for a certain amount of time. c#在一定时间内保持低 CPU 使用率。 C#
【发布时间】:2013-08-05 14:54:00
【问题描述】:

我有以下代码,它只允许我的应用程序在 CPU 使用率低于一定时间后打开。但是我只需要一些帮助来添加一些东西,以确保使用率保持在这个低水平至少 5 秒,这样我就可以避免 CPU 使用率的任何下降峰值。

cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
var usage = cpuUsage.NextValue();
do
{
    Thread.Sleep(TimeSpan.FromSeconds(1));
    usage = cpuUsage.NextValue();
    Console.WriteLine(usage + "%");
} while (usage > 10.00);

Process proc = new Process();
proc.StartInfo = new ProcessStartInfo(@"C:\Documents and Settings\rcgames\Desktop\Game1.exe");
proc.Start();

【问题讨论】:

  • 您是否尝试过任何方法来实现这一目标?
  • 不...我考虑过添加一个休眠的 for 循环?
  • 我还不能百分百确定。这就是为什么我要征求建议@venson
  • 不,我的意思是,该代码的目的是什么?你想做什么?为什么要那样做?
  • 如果它在 5 内保持低于 10%,然后您开始游戏,然后突然出现 CPU 峰值,会发生什么情况?那时,您对这段特定代码一无所获。如果游戏是 CPU 密集型游戏,我会反对在无法处理它的机器上运行它。我同意@Venson 的观点,你到底想用这个来完成什么,我认为需要更多细节。

标签: c# cpu-usage performancecounter


【解决方案1】:
int secondsWhileLowUsage = 0;     
do {
    cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    var usage = cpuUsage.NextValue();
    do
    {
        Thread.Sleep(TimeSpan.FromSeconds(1));
        usage = cpuUsage.NextValue();
        if (usage > 10.00)
            secondsWhileLowUsage = 0;

        Console.WriteLine(usage + "%");
    } while (usage > 10.00);
    secondsWhileLowUsage ++; 
} while (secondsWhileLowUsage < 5)

Process proc = new Process();
proc.StartInfo = new ProcessStartInfo(@"C:\Documents and Settings\rcgames\Desktop\Game1.exe");
proc.Start();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2018-12-13
    • 2023-03-27
    • 2020-09-27
    • 2020-12-16
    • 2012-02-17
    • 1970-01-01
    相关资源
    最近更新 更多