12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- // See https://aka.ms/new-console-template for more information
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Threading;
- internal class Program
- {
- private static void Main(string[] args)
- {
- Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
- var counter = new PerformanceCounter("System", "Processor Queue Length", null);
- Console.WriteLine(counter.NextValue());
- //ShowCpuLoadByKernelIdleTime();
- }
- private static void ShowCpuLoadByKernelIdleTime()
- {
- var a = GetIdleKernelTime();
- if (a.HasValue == false)
- {
- Console.WriteLine("ERROR A");
- return;
- }
- Thread.Sleep(1000);
- var b = GetIdleKernelTime();
- if (b.HasValue == false)
- {
- Console.WriteLine("ERROR B");
- return;
- }
- var d = (b.Value - a.Value);
- var p = d / Environment.ProcessorCount;
- var i = d / 1000000000.0;
- Console.WriteLine($"{i * 100:N2}");
- }
- private static long? GetIdleKernelTime()
- {
- var outputs = RunCmd("wmic", "Process", "where", "ProcessId=0", "get", "KernelModeTime", "/value");
- var kv = outputs.FirstOrDefault(s => string.IsNullOrEmpty(s) == false);
- if (kv != null)
- {
- var kvs = kv.Split('=', 2);
- if (kvs.Length == 2 && long.TryParse(kvs[1], out var ns100)) return ns100;
- }
- return null;
- }
- private static IReadOnlyList<string> RunCmd(string filename, params string[] args)
- {
- var outputs = new List<string>();
- var p = new Process();
- p.StartInfo.FileName = filename;
- foreach (var s in args) p.StartInfo.ArgumentList.Add(s);
- p.StartInfo.RedirectStandardOutput = true;
- p.StartInfo.UseShellExecute = false;
- p.OutputDataReceived += (sender, eventArgs) => outputs.Add(eventArgs.Data);
- p.Start();
- p.BeginOutputReadLine();
- p.WaitForExit();
- return outputs;
- }
- }
|