以下文章来源于微信公众号DotNetCore实战

在 .NET Framework 中,很多人会用 PerformanceCounter 类做这件事情,

如下代码:
` public class Program
{
public static void Main(string[] args)
{
while (true)
{
var cpuUsage = GetCpuUsageForProcess();

  1. Console.WriteLine(cpuUsage);
  2. }
  3. }
  4. private static int GetCpuUsageForProcess()
  5. {
  6. var currentProcessName = Process.GetCurrentProcess().ProcessName;
  7. var cpuCounter = new PerformanceCounter("Process", "% Processor Time", currentProcessName);
  8. cpuCounter.NextValue();
  9. return (int)cpuCounter.NextValue();
  10. }
  11. }`

但 PerformanceCounter 在.NETCore 中是没有的,所以只能采用其他方式了,其实在 System.Diagnostics.Process 类中有一个 TotalProcessorTime 属性,它可以准实时的统计当前进程所消耗的CPU处理器时间,

如下代码:
`class Program
{
public static async Task Main(string[] args)
{
var task = Task.Run(() => ConsumeCPU(50));

  1. while (true)
  2. {
  3. await Task.Delay(2000);
  4. var cpuUsage = await GetCpuUsageForProcess();
  5. Console.WriteLine(cpuUsage);
  6. }
  7. }
  8. public static void ConsumeCPU(int percentage)
  9. {
  10. Stopwatch watch = new Stopwatch();
  11. watch.Start();
  12. while (true)
  13. {
  14. if (watch.ElapsedMilliseconds > percentage)
  15. {
  16. Thread.Sleep(100 - percentage);
  17. watch.Reset();
  18. watch.Start();
  19. }
  20. }
  21. }
  22. private static async Task<double> GetCpuUsageForProcess()
  23. {
  24. var startTime = DateTime.UtcNow;
  25. var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
  26. await Task.Delay(500);
  27. var endTime = DateTime.UtcNow;
  28. var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
  29. var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
  30. var totalMsPassed = (endTime - startTime).TotalMilliseconds;
  31. var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
  32. return cpuUsageTotal * 100;
  33. }
  34. }`


可以看到程序每2s输出一次,观察到 output 和 任务管理器 中的CPU利用率基本是一致的。

更多相关文章

  1. android代码混淆
  2. Android(安卓)Studio GitHub 提交项目代码
  3. Android(安卓)判断网络状态,并且在没有网络的时候,打开网络设置对
  4. 在Cocos2d-x中处理Android(安卓)系统设备的Menu和Back按键的响应
  5. 第一行代码 Android读书笔记(一)
  6. Android源码下载并绑定到Eclipse中
  7. Android: Service中创建窗口Dialog
  8. Android最基本的异步网络请求框架
  9. android访问远程数据库

随机推荐

  1. python函数的属性
  2. Django 连接 Mysql (8.0.16) 失败
  3. python_列表_循环遍历
  4. 应用Python开发WebService服务端及客户端
  5. 【Python】logging结合decorator模式实优
  6. python接入微博第三方API之2接入用户登录
  7. Python开发利器——wingIDE破解技巧
  8. python subprocess模块 监控子进程的2种
  9. python 的基础 学习 11天 作业题
  10. Django i18n:为{% blocktrans %}块推荐的