如何在C#中生成稳定的CPU负载,在一定时间内低于100%?我还希望能够在一段时间后更改负载量.您如何建议在很短的时间内产生使用峰值?
Isa*_*avo 56
首先,您必须了解CPU使用率始终是特定时间内的平均值.在任何给定的时间,CPU正在工作或不工作.CPU永远不会40%工作.
但是,我们可以通过让CPU工作0.4秒并睡眠0.6秒来模拟40%的负载.这使得平均利用率达到40%.
将其减少到小于一秒,比如说100毫秒的块应该可以提供更稳定的利用率.
以下方法将采用所需利用率的参数,然后将单个CPU /核心用于该程度:
public static void ConsumeCPU(int percentage)
{
if (percentage < 0 || percentage > 100)
throw new ArgumentException("percentage");
Stopwatch watch = new Stopwatch();
watch.Start();
while (true)
{
// Make the loop go on for "percentage" milliseconds then sleep the
// remaining percentage milliseconds. So 40% utilization means work 40ms and sleep 60ms
if (watch.ElapsedMilliseconds > percentage)
{
Thread.Sleep(100 - percentage);
watch.Reset();
watch.Start();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里使用秒表是因为它比TickCount属性更准确,但您也可以使用它并使用减法来检查您是否已经运行足够长时间.
要记住两件事:
要回答第二个问题,关于在一定时间后更改利用率,我建议您在一个或多个线程上运行此方法(取决于核心数量),然后当您想要更改利用率时,您只需停止这些线程并生成新线程使用新的百分比值.这样,您就不必实现线程通信来更改percentage正在运行的线程.
Gui*_*non 16
只是添加了Isak响应,我在这里简单介绍了多核:
public static void CPUKill(object cpuUsage)
{
Parallel.For(0, 1, new Action<int>((int i) =>
{
Stopwatch watch = new Stopwatch();
watch.Start();
while (true)
{
if (watch.ElapsedMilliseconds > (int)cpuUsage)
{
Thread.Sleep(100 - (int)cpuUsage);
watch.Reset();
watch.Start();
}
}
}));
}
static void Main(string[] args)
{
int cpuUsage = 50;
int time = 10000;
List<Thread> threads = new List<Thread>();
for (int i = 0; i < Environment.ProcessorCount; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(CPUKill));
t.Start(cpuUsage);
threads.Add(t);
}
Thread.Sleep(time);
foreach (var t in threads)
{
t.Abort();
}
}
Run Code Online (Sandbox Code Playgroud)
对于统一的压力:Isak Savo 的回答略有调整
int percentage = 80;
for (int i = 0; i < Environment.ProcessorCount; i++)
{
(new Thread(() =>
{
Stopwatch watch = new Stopwatch();
watch.Start();
while (true)
{
// Make the loop go on for "percentage" milliseconds then sleep the
// remaining percentage milliseconds. So 40% utilization means work 40ms and sleep 60ms
if (watch.ElapsedMilliseconds > percentage)
{
Thread.Sleep(100 - percentage);
watch.Reset();
watch.Start();
}
}
})).Start();
}
Run Code Online (Sandbox Code Playgroud)