批处理获取某个进程的CPU使用率

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了批处理获取某个进程的CPU使用率相关的知识,希望对你有一定的参考价值。

目前我已经做了一部分工作
我没有找到一步求出CPU使用率的方法,只能用内核时间/用户时间来计算某个进程的CPU使用率

@echo off
TITLE RelayServer Check
wmic process where name="explorer.exe" get KernelModeTime,UserModeTime /value > C:\cputime.txt
for /f "tokens=1* delims=" %%a in ('findstr /n .* C:\cputime.txt') do if not "%%b"=="" set st%%a=%%b
goto END
....
:END

PS.这段代码是有问题的
wmic process where name="explorer.exe" get KernelModeTime,UserModeTime /value > C:\cputime.txt
这一句已经把 explorer.exe 进程的内核态时间和用户态时间写入到 C:\cputime.txt 中了
格式类似于

KernelModeTime=1334062500
UserModeTime=295937500

但是cputime.txt文件前两行是空行
后一句
for /f "tokens=1* delims=" %%a in ('findstr /n .* C:\cputime.txt') do if not "%%b"=="" set st%%a=%%b
本应该读出数据来然后再解析的....不过老出错,我也不清楚什么原因
希望高手出手
将 内核态时间 和 用户态时间 分别赋值给两个变量~_~ 最好是能把值直接付给变量
如果顺手计算一下 KernelModeTime / UserModeTime 就更好了~_~

参考技术A 这个delims=错了。。还有就是wmic有时候产生不是简单的空行或空格(要在16进制编辑器里才能看到),加上Findstr的BUG,所以经常出现不是想要的结果。。

@echo off&Setlocal EnableDelayedExpansion
TITLE RelayServer Check
for /f "skip=2 tokens=2 delims==" %%i in (
'wmic process where "name='explorer.exe'" get KernelModeTime^,UserModeTime /value'
) do (
set "x=!x! %%i"
)
call :Div %x% 5
>nul pause&exit /b
:Div dividend divisor [decimal] ||@by zj
::不支持超大数和浮点
Setlocal EnableDelayedExpansion
set "dnd=%~1"&set "dsr=%~2"&set "dec=%~3"
if %dsr% equ 0 echo 除数不能是0!&goto :EOF
set/a x=%dnd%/%dsr%
if %x% equ 0 (
if %dnd% lss 0 (if %dsr% gtr 0 set "x=-0") else if %dsr% lss 0 set "x=-0"
)
if not defined dec set "dec=8"
if %dec% equ 0 echo %x%&goto :EOF
for /l %%i in (1 1 %dec%) do (
set/a dnd=^(a=!dnd!%%%dsr%^)*10,b=dnd/%dsr%
set "y=!y!!b!"
)
echo CPU使用率:%x%.%y:-=%%%
Endlocal
goto :EOF

PS:如非必要建议少用wmic本回答被提问者和网友采纳

c# 获取某个进程的CPU使用百分百(类似任务管理器中显示CPU)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 进程监控
{
    class Program
    {
        static void Main(string[] args)
        {
            Process[] processes = Process.GetProcessesByName("taskmgr");
           
            foreach (Process instance in processes)
            {
                Console.WriteLine("");
                Console.WriteLine("ProcessName:" + instance.ProcessName);
                try
                {
                    //Console.WriteLine("提交大小\t" + instance.PagedMemorySize64 / 1024);
                    Console.WriteLine("工作设置(内存)\t" + instance.WorkingSet64 / 1024);
                    Console.WriteLine("线程数\t" + instance.Threads.Count);
                    Console.WriteLine("句柄数\t" + instance.HandleCount);

                }
                catch { }
            }

            Process p = processes[1];
            //PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
            //PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);


            var objQuery = new ObjectQuery("select * from Win32_Process WHERE ProcessID = " + p.Id);
            var moSearcher = new ManagementObjectSearcher(objQuery);
            DateTime firstSample = DateTime.MinValue, secondSample = DateTime.MinValue;

            double ProcessorUsage;
            double msPassed;
            ulong u_OldCPU = 0;
            while (true)
            {
                var gets = moSearcher.Get();
                foreach (ManagementObject mObj in gets)
                {
                    try
                    {
                        if (firstSample == DateTime.MinValue)
                        {
                            firstSample = DateTime.Now;
                            mObj.Get();
                            u_OldCPU = (ulong)mObj["UserModeTime"] + (ulong)mObj["KernelModeTime"];
                        }
                        else
                        {
                            secondSample = DateTime.Now;
                            mObj.Get();
                            ulong u_newCPU = (ulong)mObj["UserModeTime"] + (ulong)mObj["KernelModeTime"];

                            msPassed = (secondSample - firstSample).TotalMilliseconds;
                            ProcessorUsage = (u_newCPU - u_OldCPU) / (msPassed * 100.0 * Environment.ProcessorCount);

                            u_OldCPU = u_newCPU;
                            firstSample = secondSample;
                            Console.WriteLine("ProcessorUsage:" + (int)ProcessorUsage);
                        }
                      
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message + ex.StackTrace);
                        Console.WriteLine(ex.InnerException.Message);
                    }
                }
                Thread.Sleep(1000);
            }
            Console.ReadLine();
        }
    }
}

以上是关于批处理获取某个进程的CPU使用率的主要内容,如果未能解决你的问题,请参考以下文章

c# 获取某个进程的CPU使用百分百(类似任务管理器中显示CPU)

批处理怎样获取进程cpu使用率

centossnmp获取cpu异常

shell脚本每隔2s获取某个进程的cpu和mem数据并保存到csv文件

C#获取特定进程CPU和内存使用率

性能分析使用pidstat查看某个进程线程占用CPU情况