如何在给定负载下运行CPU (CPU利用率%)
本文关键字:CPU 利用率 运行 负载 | 更新日期: 2023-09-27 17:48:58
是否可以冻结在Windows任务管理器中显示的CPU使用情况?我希望将程序中的负载冻结为特定值,如20%,50%,70%等。
(这是为了分析PC在CPU使用方面消耗了多少功率。)
这可能吗?
我的第一个天真的尝试是生成2个线程作为核心——每个线程具有最高优先级,然后在每个线程中运行一个繁忙循环并做一些工作。(更多的线程比内核是"窃取"所有的时间,我可以从其他线程在windows:-)
使用某种API来读取CPU负载(可能是WMI或性能计数器?),然后我将使每个线程从繁忙循环中"yield"(每个循环睡眠一定数量的时间),直到我在反馈周期中获得近似负载。
这个循环会自我调节:负荷太高,睡眠更多。负荷过低,睡眠少。这不是一门精确的科学,但我认为通过一些调整可以获得稳定的负载。
但是,我不知道,真的:-)
幸福的编码。
另外,考虑电源管理——有时它可以将CPU锁定在"max %"。然后完全加载CPU,它将在该限制下达到最大值。(至少Windows 7有一个内置的功能来做到这一点,这取决于CPU和芯片组——可能有许多第三方工具。)
对于基于负载和温度等动态时钟的新cpu,情况变得相当混乱。
这是我对。net 3.5的"幼稚"方法的尝试。请确保包含System.Management
引用。
任务管理器报告的CPU利用率在我的系统上徘徊在目标的几个百分点以内——平均似乎非常接近。嗯,但是有一些调整的灵活性。
快乐编码(再次)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Threading;
using System.Diagnostics;
namespace CPULoad
{
class Program
{
// What to try to get :-)
static int TargetCpuUtilization = 50;
// An average window too large results in bad harmonics -- keep it small.
static int AverageWindow = 5;
// A somewhat large number gets better results here.
static int ThreadsPerCore = 8;
// WMI is *very slow* compared to a PerformanceCounter.
// It still works, but each cycle is *much* longer and it doesn't
// exhibit as good of characteristics in maintaining a stable load.
// (It also seems to run a few % higher).
static bool UseWMI = false;
// Not sure if this helps -- but just play about :-)
static bool UseQuestionableAverage = true;
static int CoreCount () {
var sys = new ManagementObject("Win32_ComputerSystem.Name='"" + Environment.MachineName + "'"");
return int.Parse("" + sys["NumberOfLogicalProcessors"]);
}
static Func<int> GetWmiSampler () {
var searcher = new ManagementObjectSearcher(
@"root'CIMV2",
"SELECT PercentProcessorTime FROM Win32_PerfFormattedData_PerfOS_Processor");
return () => {
var allCores = searcher.Get().OfType<ManagementObject>().First();
return int.Parse("" + allCores["PercentProcessorTime"]);
};
}
static Func<int> GetCounterSampler () {
var cpuCounter = new PerformanceCounter {
CategoryName = "Processor",
CounterName = "% Processor Time",
InstanceName = "_Total",
};
return () => {
return (int)cpuCounter.NextValue();
};
}
static Func<LinkedList<int>, int> StandardAverage () {
return (samples) => {
return (int)samples.Average();
};
}
// Bias towards newest samples
static Func<LinkedList<int>, int> QuestionableAverage () {
return (samples) => {
var weight = 4.0;
var sum = 0.0;
var max = 0.0;
foreach (var sample in samples) {
sum += sample * weight;
max += weight;
weight = Math.Min(4, Math.Max(1, weight * 0.8));
}
return (int)(sum / max);
};
}
static void Main (string[] args) {
var threadCount = CoreCount() * ThreadsPerCore;
var threads = new List<Thread>();
for (var i = 0; i < threadCount; i++) {
Console.WriteLine("Starting thread #" + i);
var thread = new Thread(() => {
Loader(
UseWMI ? GetWmiSampler() : GetCounterSampler(),
UseQuestionableAverage ? QuestionableAverage() : StandardAverage());
});
thread.IsBackground = true;
thread.Priority = ThreadPriority.Highest;
thread.Start();
threads.Add(thread);
}
Console.ReadKey();
Console.WriteLine("Fin!");
}
static void Loader (Func<int> nextSample, Func<LinkedList<int>, int> average) {
Random r = new Random();
long cycleCount = 0;
int cycleLength = 10;
int sleepDuration = 15;
int temp = 0;
var samples = new LinkedList<int>(new[] { 50 });
long totalSample = 0;
while (true) {
cycleCount++;
var busyLoops = cycleLength * 1000;
for (int i = 0; i < busyLoops; i++) {
// Do some work
temp = (int)(temp * Math.PI);
}
// Take a break
Thread.Sleep(sleepDuration);
{
// Add new sample
// This seems to work best when *after* the sleep/yield
var sample = nextSample();
if (samples.Count >= AverageWindow) {
samples.RemoveLast();
}
samples.AddFirst(sample);
totalSample += sample;
}
var avg = average(samples);
// should converge to 0
var conv = Math.Abs(TargetCpuUtilization - (int)(totalSample / cycleCount));
Console.WriteLine(string.Format("avg:{0:d2} conv:{1:d2} sleep:{2:d2} cycle-length:{3}",
avg, conv, sleepDuration, cycleLength));
// Manipulating both the sleep duration and work duration seems
// to have the best effect. We don't change both at the same
// time as that skews one with the other.
// Favor the cycle-length adjustment.
if (r.NextDouble() < 0.05) {
sleepDuration += (avg < TargetCpuUtilization) ? -1 : 1;
// Don't let sleep duration get unbounded upwards or it
// can cause badly-oscillating behavior.
sleepDuration = (int)Math.Min(24, Math.Max(0, sleepDuration));
} else {
cycleLength += (avg < TargetCpuUtilization) ? 1 : -1;
cycleLength = (int)Math.Max(5, cycleLength);
}
}
}
}
}
虽然Windows是一个抢占式操作系统,但在内核模式下运行的代码——比如驱动程序——被抢占的次数要少得多。虽然在c#中无法实现,但这应该会产生比上面更严格的负载控制方法,但也有更多的复杂性(以及崩溃整个系统的能力:-)
有Process.PriorityClass
,但将其设置为正常以外的任何东西都会产生最不一致的行为。
我不知道你是否可以这样做,但是你可以通过priority属性改变执行线程的线程优先级。你可以这样设置:
Thread.CurrentThread.Priority = ThreadPriority.Lowest;
我也不认为你真的想要限制它。如果机器在其他方面处于空闲状态,您希望它忙于执行任务,对吗?ThreadPriority帮助将此信息传递给调度器。
参考:如何限制一个c#程序的CPU使用?