- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
是否可以卡住 Windows 任务管理器中显示的 CPU 使用率?我希望将负载卡住为程序中的特定值,如 20%、50%、70% 等。
(这是为了分析 PC 在 CPU 使用率方面消耗了多少电量。)
这可能吗?
最佳答案
我的第一个天真的尝试是生成 2 个线程作为核心——每个线程都具有最高优先级,然后在每个线程内运行一个忙循环并做一些工作。 (多于核心的线程就是“窃取”我可以从 Windows 中的其他线程获得的所有时间:-)
使用某种 API 来读取 CPU 负载(也许是 WMI 或性能计数器?)然后我会让每个线程从繁忙的循环中“屈服”(每个循环休眠一定时间)直到我得到反馈周期中的近似负载。
这个循环会 self 调整:负载太高,睡得更多。负荷太低,睡得少。这不是一门精确的科学,但我认为通过一些调整可以获得稳定的负载。
但是,我真的不知道 :-)
快乐编码。
此外,请考虑电源管理——有时它可以将 CPU 锁定在“最大百分比”。然后完全加载 CPU,它将达到该极限。 (至少,Windows 7 具有执行此操作的内置功能,具体取决于 CPU 和芯片组——可能有许多第 3 方工具。)
对于基于负载和温度等动态计时的新型 CPU,情况变得相当困惑。
这是我对 .NET 3.5 的“天真”方法的尝试。确保包括 System.Management
引用。
在我的系统上,任务管理器报告的 CPU 利用率徘徊在目标的百分之几内——平均值似乎非常接近。 YMMV,但有一些调整的灵 active 。
快乐编码(再次)。
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 是抢占式操作系统,但在 Kernel Mode 中运行的代码——比如司机——被更少的人抢占。虽然在 C# AFAIK 中不可行,但这应该会产生比上述方法更严格的负载控制方法,但也有更多的复杂性(以及使整个系统崩溃的能力:-)
有Process.PriorityClass
,但将其设置为正常以外的任何值都会对我产生最不一致的行为。
关于c# - 如何在给定负载下运行 CPU(CPU 利用率百分比)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5577098/
我想知道在谈到 CPU 使用率和 CPU 利用率时,术语是否存在科学差异。我觉得这两个词都被用作同义词。它们都描述了 CPU 时间和 CPU 容量之间的关系。 Wikipedia称之为 CPU 使用率
我研究了一些关于处理器和 Tomasulo 算法的指令重新排序的内容。 为了更深入地了解这个主题,我想知道是否有任何方法可以(获取跟踪)查看为给定程序完成的实际动态重新排序? 我想给出一个输入程序并查
我有一台配备 2 个 Intel Xeon CPU E5-2620 (Sandy Bridge) 和 10Gbps 82599 NIC(2 个端口)的服务器,用于高性能计算。从 PCI 关联性中,我看
您能详细解释一下“用户 CPU 时间”和“系统 CPU 时间”吗?我读了很多,但我不太理解。 最佳答案 区别在于时间花在用户空间还是内核空间。用户 CPU 时间是处理器运行程序代码(或库中的代码)所花
我想知道如何识别 CPU 是否与 ARM v5 指令集兼容。 假设 ARM v7 指令与 ARM v5 兼容是否正确? 最佳答案 您可以阅读 CPUID base register获得PARTNO。然
我目前在具有多个六核 CPU 的服务器上使用 C 多线程。我想将我的一些线程的亲和性设置为单个 CPU 的各个核心。我使用过 pthread_setaffinity_np() 和 sched_seta
1) 独占时间是在方法中花费的时间2) 包含时间是在方法中花费的时间加上在任何被调用函数中花费的时间3)我们称调用方法为“ parent ”,称方法为“子”。引用链接:Click here 这里的问题
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 5 年前。 Improve this ques
好的,所以编译器可以出于性能原因自由地重新排序代码片段。让我们假设一些代码片段,在没有应用优化的情况下直接翻译成机器代码,看起来像这样: machine_instruction_1 machine_i
我在 zabbix 中有以下默认图表,但我不知道如何解释这些值。谁能解释一下? 最佳答案 操作系统是一件非常忙碌的事情,尤其是当你让它做某事时(即使你没有做)。当我们看到一个活跃的企业环境时,总会发生
换句话说,L1、L2、L3 等缓存是否总是反射(reflect) CPU的字节序 ? 或者总是将数据存储在某些 的缓存中更有意义吗?特定字节序 ? 有没有总体设计决策 ? 最佳答案 大多数现代缓存不会
我想知道当前的 cpus 是否避免在其中至少一个为零时将两个数字相乘。谢谢 最佳答案 这取决于 CPU 和(在某些情况下)操作数的类型。 较旧/较简单的 CPU 通常使用如下乘法算法: integer
我有一个 CUDA 应用程序,它在一台计算机(配备 GTX 275)上运行良好,而在另一台配备 GeForce 8400 的计算机上运行速度慢了大约 100 倍。我怀疑有某种回退使代码实际上在 CPU
例如,对于 8 位 CPU,堆栈大小预计为 8 位宽,16 位 CPU 与 16 位堆栈宽度,以及 32 位、64 位 CPU,等等。是否适用于所有架构? 最佳答案 CPU 具有数据总线和地址总线。它
实现 SIMD 是否需要多核 CPU? 在阅读有关 SIMD 的维基百科时,我发现了以下短语“多处理元素”。那么这句话和“多核CPU”有什么区别呢? 最佳答案 不,每个内核通常都可以执行指令集中的大多
我遗漏了一些基本的东西。 CPU 流水线:在基本层面上,为什么指令需要不同数量的时钟周期才能完成,为什么有些指令在多级 CPU 中只需要 1 个周期? 除了明显的“不同的指令需要不同的工作量才能完成”
超线程 CPU 是实现并行还是仅实现并发(上下文切换)? 我的猜测是没有并行性,只有通过上下文切换的并发性。 最佳答案 单个物理 CPU 具有超线程的核心显示为 两个逻辑 CPU 到操作系统。 CPU
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎不是关于 a specific programming problem, a softwar
背景是这样的:下周我们的办公室将有一天因为维护而没有暖气。预计室外温度在 7 至 12 摄氏度之间,因此可能会变冷。可移植电取暖器数量太少,无法满足所有人的需求。 但是,在我大约 6-8 平方米的办公
我开发了一个应用程序,该应用程序在我的开发箱上的三个容器中运行,该开发箱具有带超线程的四核,这意味着系统和 docker 使用 8 个核心。 容器的 CPU 分配由 docker-compose 完成
我是一名优秀的程序员,十分优秀!