注意:算法仅供参考。

cpuusage.cs

 using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading; namespace cpuusage
{
class Program
{
const string VERSION = "cpuusage v0.1.0";
static readonly Dictionary<string, PerformanceCounter> _caches = new Dictionary<string, PerformanceCounter>();
static string _format = "list";
static int _sleep = ;
static int _times = -;
static bool _pauseWhenFinish = false;
static StreamWriter _sw = null;
static bool _listProcessNames = false;
static bool _printUsage = false;
static bool _printVersion = false; static void Main(string[] args)
{
var processNames = GetProcessNamesAndParseArgs(args);
if (_printVersion)
{
PrintVersion();
}
if (_printUsage)
{
PrintUsage();
}
else if (_listProcessNames)
{
PrintProcessNames(processNames);
}
else
{
switch (_format)
{
case "table":
PrintToTable(processNames);
break;
case "csv":
PrintToCsv(processNames);
break;
case "list":
PrintToList(processNames);
break;
default:
Fault(, "ERROR: -f argument error");
break;
}
}
if (_pauseWhenFinish) {
Console.WriteLine();
Console.Write("Press any key to EXIT...");
Console.ReadKey(true);
}
if (_sw != null)
{
_sw.Close();
}
} static void Fault(int returnCode, string message)
{
Console.WriteLine(message);
if (_sw != null)
{
_sw.Close();
}
Environment.Exit(returnCode);
} static void PrintProcessNames(string[] processNames)
{
foreach (var name in processNames)
{
Output(string.Format("{0}{1}", name, Environment.NewLine));
}
} static void PrintToList(string[] processNames)
{
if (processNames == null || processNames.Length == )
{
return;
}
const string nameTitle = "Name";
const string cpuUsageTitle = "CPU Usage (%)";
var nameColumnMaxLength = Math.Max(processNames.Max(n => n.Length), nameTitle.Length);
var cpuUsageColumnMaxLength = cpuUsageTitle.Length;
var format = string.Format("{{0,-{0}}} {{1:0.##}}", nameColumnMaxLength);
var head = string.Format(format, nameTitle, cpuUsageTitle).ToUpper();
head += Environment.NewLine + string.Format(format, new string('-', nameColumnMaxLength), new string('-', cpuUsageColumnMaxLength));
var sb = new StringBuilder();
while (_times != )
{
sb.AppendLine(head);
foreach (var name in processNames)
{
try
{
sb.AppendFormat(format, name, GetProcessCpuUsage(name));
sb.AppendLine();
}
catch(Exception)
{
}
}
Output(sb.ToString());
sb.Clear();
if(_times > ) {
if (--_times == ) {
break;
}
}
Thread.Sleep(_sleep);
sb.AppendLine();
}
} static void PrintToTable(string[] processNames)
{
if (processNames == null || processNames.Length == )
{
return;
}
var sb = new StringBuilder();
var sb1 = new StringBuilder();
foreach (var name in processNames)
{
sb.AppendFormat("{0,-6} ", name);
sb1.AppendFormat("{0} ", new string('-', Math.Max(name.Length, )));
}
sb.Remove(sb.Length - , );
sb1.Remove(sb1.Length - , );
sb.AppendLine();
sb.Append(sb1.ToString());
sb.AppendLine();
var head = sb.ToString();
Output(head);
sb1 = null;
sb.Clear();
while (_times != )
{
for (int i = ; i < processNames.Length; i++)
{
var name = processNames[i];
var value = "";
try
{
value = GetProcessCpuUsage(name).ToString("0.00");
}
catch(Exception)
{
}
var length = Math.Max(name.Length, );
value = value.PadLeft(length);
if (i + != processNames.Length) {
value = string.Format("{0} ", value);
}
sb.Append(value);
}
Output(sb.ToString());
sb.Clear();
if(_times > ) {
if (--_times == ) {
break;
}
}
Thread.Sleep(_sleep);
sb.AppendLine();
}
} static void PrintToCsv(string[] processNames)
{
if (processNames == null || processNames.Length == )
{
return;
}
var sb = new StringBuilder();
foreach (var name in processNames)
{
var tempName = name.Replace("\"", "\"\"");
if (name.Contains(",") || name.Contains(" ") || name.Contains("\""))
{
tempName = string.Format("\"{0}\"", tempName);
}
sb.AppendFormat("{0},", tempName);
}
sb.Remove(sb.Length - , );
sb.AppendLine();
var head = sb.ToString();
Output(head);
sb.Clear();
while (_times != )
{
for (int i = ; i < processNames.Length; i++)
{
var name = processNames[i];
var value = "";
try
{
value = GetProcessCpuUsage(name).ToString("0.00");
}
catch(Exception)
{
}
if (i + != processNames.Length)
{
value = string.Format("{0},", value);
}
sb.Append(value);
}
Output(sb.ToString());
sb.Clear();
if(_times > ) {
if (--_times == ) {
break;
}
}
Thread.Sleep(_sleep);
sb.AppendLine();
}
} static string[] GetProcessNamesAndParseArgs(string[] args)
{
if (args.Any(n => n.ToLower() == "-v"))
{
_printVersion = true;
}
if (args.Length == || args.Any(n => n.ToLower() == "-h"))
{
_printUsage = true;
_printVersion = true;
_pauseWhenFinish = true;
return null;
}
_pauseWhenFinish = args.Any(n => n.ToLower() == "-p");
if (args.Any(n => n.ToLower() == "-l"))
{
_listProcessNames = true;
}
var arg = args.FirstOrDefault(n => n.ToLower().StartsWith("-f:"));
if (arg != null) {
_format = arg.Substring().ToLower();
}
arg = args.FirstOrDefault(n => n.ToLower().StartsWith("-s"));
if (arg != null) {
int s;
if (int.TryParse(arg.Substring(), out s)) {
_sleep = s;
}
}
arg = args.FirstOrDefault(n => n.ToLower().StartsWith("-t"));
if (arg != null) {
int t;
if (int.TryParse(arg.Substring(), out t)) {
_times = t;
}
}
arg = args.FirstOrDefault(n => n.ToLower().StartsWith("-o:"));
if (arg != null) {
var output = arg.Substring().ToLower();
try
{
_sw = File.CreateText(output);
}
catch(Exception ex)
{
if (_sw != null)
{
_sw.Close();
}
_sw = null;
Fault(, string.Format("ERROR: {0}", ex.Message));
}
} if (args.Contains("*"))
{
return Process.GetProcesses().Select(n => n.ProcessName).OrderBy(n => n).Distinct().ToArray();
} var r = args.Where(n => !n.StartsWith("-")).Select(n => GetFriendlyName(n)).ToArray();
if (_listProcessNames && r.Length == )
{
return Process.GetProcesses().Select(n => n.ProcessName).OrderBy(n => n).Distinct().ToArray();
}
return r;
} static void Output(string message)
{
Console.Write(message);
if (_sw == null)
{
return;
}
try
{
_sw.Write(message);
_sw.Flush();
}
catch (Exception)
{
_sw.Close();
_sw = null;
}
} static void PrintUsage()
{
var n = Path.GetFileName(Environment.GetCommandLineArgs()[]);
var n1 = Path.GetFileNameWithoutExtension(n);
Console.Write("Usage:{2} {0} [-f:<list|table|csv>] [-s<milliseconds>] [-t<times>] [-o:<filename>] [-p] <instance_names|*>{2} {0} -l [-o:<filename>] [-p] [<instance_names|*>]{2} -f output format, default to list.{2} -s sleep millisenconds, default to 1000.{2} -t times, default to forever.{2} -p pause when out of times.{2} -o output to file.{2} -l print name of processes only.{2} -h print help.{2} -v print version.{2}{2}Example:{2} {0} _Total Idle System Svchost {1}{2} {0} *{2} {0} * -f:csv -s200 -t10 > 1.csv{2} {0} -f:csv -s200 -t10 chrome firefox -o:2.csv{2}", n, n1, Environment.NewLine);
} static void PrintVersion()
{
Console.WriteLine(VERSION);
} static string GetFriendlyName(string instanceName)
{
var r = new StringBuilder(instanceName);
for(int i=; i<r.Length; i++)
{
var ch = r[i];
if (ch=='(')
{
r[i] = '[';
continue;
}
if (ch==')')
{
r[i] = ']';
continue;
}
if (ch=='#' || ch=='\\' || ch== '/')
{
r[i] = '_';
continue;
}
}
return r.ToString();
} static float GetProcessCpuUsage(string instanceName)
{
// var total = GetPerformanceCounter("_Total").NextValue();
var value = GetPerformanceCounter(instanceName).NextValue();
return value / Environment.ProcessorCount;
} static PerformanceCounter GetPerformanceCounter(string instanceName)
{
PerformanceCounter r;
if (_caches.TryGetValue(instanceName, out r))
{
return r;
}
r = new PerformanceCounter("Process", "% Processor Time", instanceName);
_caches[instanceName] = r;
return r;
} }
}

build.bat

 @echo off
pushd "%~dp0"
set csfile=cpuusage.cs
set PATH="C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\bin\Roslyn";"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin\Roslyn";"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\bin\Roslyn";"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64";"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN";C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319;C:\WINDOWS\Microsoft.NET\Framework64\v3.5;C:\WINDOWS\Microsoft.NET\Framework64\v2.0;%PATH%
csc.exe /target:exe /unsafe+ %csfile%
if ERRORLEVEL 1 (echo ERROR: %ERRORLEVEL%) else (echo Build Success)
echo.
echo Press any key to EXIT...
pause>nul
popd

测试:将全部进程10秒中内的CPU使用率导出到CSV,然后查看图表(排除idle和cpuusage)。

C:\> cpuusage -t10 -s1000 -f:csv * > 1.csv

CPU Usage (C#) 测试的更多相关文章

  1. CPU利用率和CPU负荷(CPU usage vs CPU load)

    对于CPU的性能监测,通常用top指令能显示出两个指标:cpu 利用率和cpu负荷. 其中%Cpu相关的内容: us表示用户进程cpu利用率,sy表示系统内核进程cpu利用率,ni表示运行正常进程消耗 ...

  2. Unity Profiler CPU Usage(CPU使用情况)

    在Profiler界面点击左侧CPU Usage,Profiler界面下方Hierarchy窗口会列出各个函数对当前CPU的耗时,从大到小排序. 然后分析,各个函数的耗时是否异常,分析有没有可以优化的 ...

  3. How to Limit NodeRunner.exe High Memory, CPU Usage

    roblem: NodeRunner.exe is consuming a lot of memory and CPU resulted in performance issues on ShareP ...

  4. Docker CPU Usage

    背景 当一台机器上跑有多个 Docker Container 的时候,我们需要知道,哪些容器占用了多少资源.采集这些指标,来让我们可以更加好的分配资源给每个 Container. 获取容器CPU使用率 ...

  5. Docker容器CPU限制选项测试

    目录 Docker容器CPU限制选项测试 参考 实验环境 --cpu-shares选项 测试 结论 --cpus选项 测试 结论 --cpuset-cpus选项 测试 结论 Docker容器CPU限制 ...

  6. C++第四十二篇 -- CPU Usage

    前言 目的:读取并控制CPU占用率 近期在做CPU Usage方面的事情,让CPU以一种高占用率的状态运行一定的时间,需要读取CPU各个核的占用率,网上关于这方面的资料好少,FQ也只找到了一个WMI的 ...

  7. 【DPDK】【CPU usage】DPDK应用如何计算当前系统的压力

    [前言] 使用DPDK开发的朋友应该都了解使用dpdk的fwd线程的工作模式是polling模式,即100%轮询的方式去加速网络IO,这样我们在操作系统层面上来观察目标processer会发现usag ...

  8. 关于CPU亲和性的测试

    今天看到运维的同事在配置nginx的CPU亲和性时候,运维同事说他在所有的机器上都是按照8核的方式来配置worker进程的CPU亲和性的. 但我觉得就是有点不太对劲,就查了一下nginx的处理work ...

  9. CPU特性漏洞测试(Meltdown and Spectre)

    2018年1月4日,国外安全研究人员披露了名为"Meltdown"和"Spectre"两组CPU特性漏洞,该漏洞波及到近20年的Intel, AMD, Qual ...

随机推荐

  1. java容器的线程安全性

    参考:https://www.cnblogs.com/yjd_hycf_space/p/7760248.html 线程安全的: Vector HashTable StringBuffer 线程不安全的 ...

  2. django中的setting全局变量的导入

    需求:在py文件中导入settings.py中的变量BASE_DIR settings.py文件 import os # Build paths inside the project like thi ...

  3. MySQL数据库(5)- pymysql的使用、索引

    一.pymysql模块的使用 1.pymysql的下载和使用 之前我们都是通过MySQL自带的命令行客户端工具mysql来操作数据库,那如何在python程序中操作数据库呢?这就需要用到pymysql ...

  4. Andrew Ng机器学习编程作业:Anomaly Detection and Recommender Systems

    作业文件 machine-learning-ex8 在本次练习,第一节我们将实现异常检测算法,并把它应用到检测网络故障服务器上.在第二部分,我们将使用协同过滤来构建电影推荐系统. 1. 异常检测 在这 ...

  5. mysql 内置功能 函数 date_format函数

    创建数据库db12 create database db12 charset=utf8; use db12; 准备表和记录 CREATE TABLE blog ( id INT PRIMARY KEY ...

  6. HDU1838:Chessboard(线性dp)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1838 这题也挺不错的.首先题目说了,棋盘的右下角一定是'1',另外棋盘里面至少包含一个1,所以最小值是1, ...

  7. 移动端笔记——jQuery touch事件

    判断移动端还是pc端 function IsPC() { var userAgentInfo = navigator.userAgent; var Agents = new Array("A ...

  8. uva 11752 The Super Powers (数论+枚举)

    题意:找出1~2^64-1中 能写成至少两个数的幂形式的数,再按顺序输出 分析:只有幂是合数的数才是符合要求的.而幂不会超过64,预处理出64以内的合数. 因为最小的合数是4,所以枚举的上限是2的16 ...

  9. 理解盒模型——外边距、内边距和边框之间的关系,IE 8以下版本的浏览器中的盒模型有什么不同。

    一个元素盒模型的层次从内到外分别为:内边距.边框和外边距IE8以下浏览器的盒模型中定义的元素的宽高不包括内边距和边框

  10. 入职第一个项目bug总结-2018/07/28

    此项目是正式入职后的第一个项目,可能各种原因重重,导致测试提出了如此多的bug,关于那些因为需求不清楚而导致的就不说了,bug总结如下: 一.ElementUI table组件出现横向滚动条 原因:因 ...