模拟稳定CPU负载和尖峰 [英] Simulate steady CPU load and spikes

查看:258
本文介绍了模拟稳定CPU负载和尖峰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能生成C#稳定的CPU负载,低于100%一段时间?我还希望能在一定的时间周期后改变的负载量。你怎么推荐产生使用高峰期很短的时间?

How could I generate steady CPU load in C#, lower than 100% for a certain time? I would also like to be able to change the load amount after a certain period of time. How do you recommend to generate usage spikes for a very short time?

推荐答案

首先,你必须明白,CPU使用率始终是在一定时间的平均值。在任何给定的时间时,CPU可以是工作或不是。 CPU是从来没有40%的工作。

First off, you have to understand that CPU usage is always an average over a certain time. At any given time, the CPU is either working or it is not. The CPU is never 40% working.

我们可以,但是,模拟40%负载以上说的第二个由具有0.4秒的CPU工作和睡觉0.6秒。这给了40%的平均使用率超过了第二位。

We can, however, simulate a 40% load over say a second by having the CPU work for 0.4 seconds and sleep 0.6 seconds. That gives an average utilization of 40% over that second.

切割下来到小于一秒,说100毫秒块应该给予更稳定的利用率。

Cutting it down to smaller than one second, say 100 millisecond chunks should give even more stable utilization.

下面的方法将采取需要利用一个参数,然后利用一个单一的CPU /核心学位:

The following method will take an argument that is desired utilization and then utilize a single CPU/core to that degree:

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();
        }
    }
}

我使用的是秒表这里,因为它比更准确在该计时单位计数的属性,但你同样可以使用并用减法检查如果你已经运行了足够长的时间。

I'm using a stopwatch here because it is more accurate than the the TickCount property, but you could likewise use that and use subtraction to check if you've run long enough.

两件事情要记住:


  • 在多核心系统,你将不得不派生一个线程每个核心。否则,你会看到被行使,只有一个CPU /核心提供大约个/数的-核心的利用率。

  • Thread.sleep代码不是很准确。它永远不会保证准确时间为毫秒,所以你会看到你的结果一些变化

要回答你的第二个问题,关于一定时间后更改利用率,我建议你在一个或多个线程(根据核数)并运行此方法,那么,当你想改变利用你只是停止这些线程,催生新百分比值新的。这样,你就不必实现线程通信改变百分比正在运行的线程。

To answer your second question, about changing the utilization after a certain time, I suggest you run this method on one or more threads (depending on number of cores) and then when you want to change utilization you just stop those threads and spawn new ones with the new percentage values. That way, you don't have to implement thread communication to change percentage of a running thread.

这篇关于模拟稳定CPU负载和尖峰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆