如何获取 C# 中的总处理器时间?

发布于 2024-11-03 04:26:25 字数 230 浏览 5 评论 0原文

我已经研究了很多,但我能找到的只是如何获得单个处理时间。

Process p = exampleProcess
return p.TotalProcessorTime

如何获得总处理器时间?如果我执行以下操作,我会获得该进程的 CPU 使用率百分比吗

return p/totalProcessorTime

I've researched a lot but all I can find is how to get the a single process time.

Process p = exampleProcess
return p.TotalProcessorTime

How can I get the total processor time? Will I get the % CPU usage of that process if I perform:

return p/totalProcessorTime

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏了南城 2024-11-10 04:26:25

您可以使用 PerformanceCounter

PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
double currentCpuPercent = cpuCounter.NextValue();

You can use PerformanceCounter:

PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
double currentCpuPercent = cpuCounter.NextValue();
三生一梦 2024-11-10 04:26:25

不,您不能将 Process 除以 TimespanTotalProcessorTime 是对执行代码实际花费的时间的度量。这是一个绝对数字。如果您想要一个相对数字,那么您需要测量该进程已经运行了多长时间。从ExitTime 中减去StartTime。像这样:

Process prc = /* something */
var wallTime = DateTime.Now - prc.StartTime;
if (prc.HasExited) wallTime = prc.ExitTime - prc.StartTime;
var procTime = prc.TotalProcessorTime;
var cpuUsage = 100 * procTime.TotalMilliseconds / wallTime.TotalMilliseconds;

Nah, you can't divide a Process by a Timespan. TotalProcessorTime is a measurement of how much time was actually spent executing code. It is an absolute number. If you want a relative number then you need to measure how long the process has been running. Subtract StartTime from ExitTime. Like this:

Process prc = /* something */
var wallTime = DateTime.Now - prc.StartTime;
if (prc.HasExited) wallTime = prc.ExitTime - prc.StartTime;
var procTime = prc.TotalProcessorTime;
var cpuUsage = 100 * procTime.TotalMilliseconds / wallTime.TotalMilliseconds;
意中人 2024-11-10 04:26:25

您想要总处理器时间,而不限于单个进程,对吗?这是否意味着您需要系统上所有进程的处理器时间?那不是和系统启动以来经过的挂墙时间一样吗?如果是这样,GetTickCount64 就可以解决问题。

You want the total processor time, not limited to a single process, correct? Does that mean you want the processor time for all processes on the system? Wouldn't that be the same as the elapsed wall time since the system was started? If so, GetTickCount64 will do the trick.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文