C# 程序可以以某种方式测量自己的 CPU 使用率吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/275957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can a C# program measure its own CPU usage somehow?
提问by Lasse V. Karlsen
I am working on a background program that will be running for a long time, and I have a external logging program (SmartInspect) that I want to feed with some values periodically, to monitor it in realtime when debugging.
我正在开发一个将运行很长时间的后台程序,我有一个外部日志程序 ( SmartInspect),我想定期提供一些值,以便在调试时实时监控它。
I know I can simply fire up multiple programs, like the Task Manager, or IARSN TaskInfo, but I'd like to keep everything in my own program for this, as I also wants to add some simple rules like if the program uses more than X% CPU, flag this in the log.
我知道我可以简单地启动多个程序,例如任务管理器或 IARSN TaskInfo,但我想为此将所有内容保留在我自己的程序中,因为我还想添加一些简单的规则,例如程序是否使用超过X% CPU,在日志中标记它。
I have a background thread that periodically feeds some statistics to SmartInspect, like memory consumption, working set, etc.
我有一个后台线程,它会定期向 SmartInspect 提供一些统计信息,例如内存消耗、工作集等。
Is it possible for this thread to get a reasonably accurate measure of how much of the computer's CPU resources it consumes? The main program is a single-threaded application (apart from the watchdog thread that logs statistics) so if a technique is limited to how much does a single thread usethen that would be good too.
该线程是否可以合理准确地衡量它消耗了多少计算机的 CPU 资源?主程序是一个单线程应用程序(除了记录统计信息的看门狗线程),所以如果一项技术仅限于单线程使用多少,那么这也很好。
I found some entries related to something called rusagefor Linux and C. Is there something similar I can use for this?
我发现了一些与Linux 和 C 的rusage相关的条目。有没有类似的东西我可以用来做这个?
Edit:Ok, I tried the performance counter way, but it added quite a lot of GC-data each time called, so the graph for memory usage and garbage collection skyrocketed. I guess I'll just leave this part out for now.
编辑:好的,我尝试了性能计数器方式,但每次调用它都会添加相当多的 GC 数据,因此内存使用和垃圾收集的图表猛增。我想我现在就把这部分放在一边。
采纳答案by axk
You can also use System.Diagnostics.Process.TotalProcessorTimeand System.Diagnostics.ProcessThread.TotalProcessorTimeproperties to calculate your processor usage as this articledescribes.
您还可以使用System.Diagnostics。Process.TotalProcessorTime和System.Diagnostics。ProcessThread.TotalProcessorTime属性来计算您的处理器使用情况,如本文所述。
回答by Sunlight
Have a look at System.Diagnostics.PerformanceCounter
. If you run up perfmon.exe
, you'll see the range of performance counters available to you (set the 'performance object' to 'Process'), one of which is '% Processor Time'.
看看System.Diagnostics.PerformanceCounter
。如果运行 up perfmon.exe
,您将看到可用的性能计数器范围(将“性能对象”设置为“进程”),其中之一是“% Processor Time”。
回答by Keltex
You can through the System.Diagnostic.PerformanceCounter class. Here's an example of somebody monitoring CPU usage:
您可以通过 System.Diagnostic.PerformanceCounter 类。这是某人监视 CPU 使用情况的示例:
Note that this does require elevated privileges. And there may be a performance hit using it.
请注意,这确实需要提升权限。使用它可能会影响性能。
回答by sundar venugopal
It is good that you are logging to monitors like smartinspect. But windows itself gathers the data for each resource in this case your program (or process). WMI is the standard for Application monitoring. We can view the data captured by WMI. Many application management, health monitoring or applicaiton monitoring tools support WMI out of the box.
您可以登录到 smartinspect 等监视器,这很好。但是在这种情况下,Windows 本身会为您的程序(或进程)收集每个资源的数据。WMI 是应用程序监控的标准。我们可以查看 WMI 捕获的数据。许多应用程序管理、健康监控或应用程序监控工具都支持开箱即用的 WMI。
So I would not recommend you to log your CPU usage within the application to a log file.
因此,我不建议您将应用程序中的 CPU 使用率记录到日志文件中。
If you think availablity and performance is critical then go for solutions like Microsoft Operations manager solution.
如果您认为可用性和性能至关重要,那么请选择 Microsoft Operations Manager 解决方案等解决方案。
To get an idea about WMI and to get the list of process see below:
- Win32_PerfFormattedData_PerfProc_Process
to get Cpu time, filter is processID
See this article- You can get the processID from Win32_process class.
要了解 WMI 并获取进程列表,请参见以下内容: -Win32_PerfFormattedData_PerfProc_Process
获取 Cpu 时间,过滤器为 processID
参见本文- 您可以从 Win32_process 类获取 processID。
WMI Made Easy For C#by Kevin Matthew Goss
WMI Made Easy For C#by Kevin Matthew Goss
oConn.Username = "JohnDoe";
oConn.Password = "JohnsPass";
System.Management.ManagementScope oMs = new System.Management.ManagementScope("\MachineX", oConn);
//get Fixed disk stats
System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3");
//Execute the query
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs,oQuery);
//Get the results
ManagementObjectCollection oReturnCollection = oSearcher.Get();
//loop through found drives and write out info
foreach( ManagementObject oReturn in oReturnCollection )
{
// Disk name
Console.WriteLine("Name : " + oReturn["Name"].ToString());
// Free Space in bytes
Console.WriteLine("FreeSpace: " + oReturn["FreeSpace"].ToString());
// Size in bytes
Console.WriteLine("Size: " + oReturn["Size"].ToString());
}
You can monitor the process from Remote system as well.
您也可以从远程系统监控进程。
回答by Ashley Davis
This code project article describes how to use the high performance timer:
本代码项目文章介绍了如何使用高性能定时器:
http://www.codeproject.com/KB/cs/highperformancetimercshar.aspx
http://www.codeproject.com/KB/cs/highperformancetimercshar.aspx
You can use it to time the execution of your code.
您可以使用它来计时代码的执行。
Here you can find a number of open source C# profilers:
在这里您可以找到许多开源 C# 分析器: