如何在C#中生成稳定的CPU负载,在一段时间内低于100%?我还希望能够在一段时间后更改负载量。您如何建议在很短的时间内产生使用峰值?
答案 0 :(得分:52)
首先,您必须了解CPU使用率始终是特定时间内的平均值。在任何给定的时间,CPU正在工作或不工作。 CPU永远不会40%工作。
然而,我们可以通过让CPU工作0.4秒并睡眠0.6秒来模拟40%的负载。这使得平均利用率达到40%。将其缩小到小于1秒,比如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();
}
}
}
我在这里使用stopwatch,因为它比TickCount属性更准确,但您也可以使用它并使用减法检查您是否已经运行足够长时间。
要记住两件事:
要回答第二个问题,关于在一段时间后更改利用率,我建议您在一个或多个线程上运行此方法(取决于核心数),然后当您想要更改利用率时,您只需停止这些线程和使用新的百分比值生成新的。这样,您就不必实现线程通信来更改正在运行的线程的percentage
。
答案 1 :(得分:15)
只是添加了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();
}
}
答案 2 :(得分:3)
对于统一的压力: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();
}
答案 3 :(得分:1)
每次必须设置cpuUsageIncreaseby变量。 例如:
1- Cpu%增加&gt; cpuUsageIncreaseby%一分钟。 2-下降到0%,持续20秒。 3-转到第1步。
private void test()
{
int cpuUsageIncreaseby = 10;
while (true)
{
for (int i = 0; i < 4; i++)
{
//Console.WriteLine("am running ");
//DateTime start = DateTime.Now;
int cpuUsage = cpuUsageIncreaseby;
int time = 60000; // duration for cpu must increase for process...
List<Thread> threads = new List<Thread>();
for (int j = 0; j < Environment.ProcessorCount; j++)
{
Thread t = new Thread(new ParameterizedThreadStart(CPUKill));
t.Start(cpuUsage);
threads.Add(t);
}
Thread.Sleep(time);
foreach (var t in threads)
{
t.Abort();
}
//DateTime end = DateTime.Now;
//TimeSpan span = end.Subtract(start);
//Console.WriteLine("Time Difference (seconds): " + span.Seconds);
//Console.WriteLine("10 sec wait... for another.");
cpuUsageIncreaseby = cpuUsageIncreaseby + 10;
System.Threading.Thread.Sleep(20000);
}
}
}