GVKun编程网logo

计算Windows进程的CPU使用率?(windows进程cpu占用100%)

9

在本文中,我们将给您介绍关于计算Windows进程的CPU使用率?的详细内容,并且为您解答windows进程cpu占用100%的相关问题,此外,我们还将为您提供关于c–如何在Windows上限制进程的

在本文中,我们将给您介绍关于计算Windows进程的CPU使用率?的详细内容,并且为您解答windows进程cpu占用100%的相关问题,此外,我们还将为您提供关于c – 如何在Windows上限制进程的CPU使用率?、c# – 如何限制进程的CPU使用率、C#系统CPU使用率并与Windows任务管理器同步、Delphi 获得每个进程的CPU使用率的知识。

本文目录一览:

计算Windows进程的CPU使用率?(windows进程cpu占用100%)

计算Windows进程的CPU使用率?(windows进程cpu占用100%)

给定一个进程ID,我怎样才能从这个进程的C#加载cpu的负载?

我已经尝试使用PerformanceCounter在c#中所述计算特定应用程序的cpu使用率

我还尝试在一个时间范围内手动取得进程的总cpu时间的两个值,并将delta-cpu-time与delta-total-time分开。

这两种方法似乎一开始工作正常,但如果我把我的应用程序旁边的Windows任务pipe理器我的应用程序总是显示约两倍的任务pipe理器。 我试图用10ms到10sec的各种时间步长进行更新,并一直得到相同的结果。

我可以在Windows XP或7上使用最新的.NET框架吗?

Windows CE 5.0 HTTPD < – > .NET应用程序

在尝试使用Windows的mono-4.2.2时,请保持Exec格式错误

在安装期间检测并要求安装Windows QFE /补丁程序

在C#中将两个方法分组在一起

嗯,当我写这个时,意识到这可能是某种双核问题。

无法强制Webbrowser控件使用当前版本的IE呈现

如何解决在C#Windows服务处理泄漏

给定一个IntPtr句柄,改变窗口的背景颜色

在64位操作系统上将Anycpu应用程序作为32位运行

当声音输出停止时,使用Powershell自动点击鼠标?

如果您有两个内核,任务管理器将报告1个cpu的100%使用率为50%。 这可能是你的问题。

c – 如何在Windows上限制进程的CPU使用率?

c – 如何在Windows上限制进程的CPU使用率?

我需要将应用程序的cpu使用率控制到一定限度.我的应用程序将在Win XP,Vista,Win7和 Windows 8上运行.

我尝试实现以获取当前进程的cpu使用率并使用Sleep()方法.(我使用了API GetProcesstimes& GetSystemTimes)

伪代码:

for(;;)
    {
         //Get the current process's cpu Usage
         int cpuUsage  = CalculatecpuUsage();
         if(cpuUsage > 50)
             Sleep(10)
         else
        {
           //Project implementation code
        }    
    }

题:

我是否可以编写应用程序来监视进程的cpu使用率,并且只要cpu达到允许的限制,就停止进程并继续进行.

在此先感谢您的帮助.

解决方法

如果你只是试图给进程一个较低的优先级以便更好地使用其他线程,你可以使用SetThreadPriority设置它的优先级,例如:

SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_BELOW_norMAL);

c# – 如何限制进程的CPU使用率

c# – 如何限制进程的CPU使用率

我想创建一个程序,即使在计算机空闲时也可以限制一个进程的cpu使用.
我已经制定了一个程序来设置进程的优先级,但如果计算机空闲,那么cpu的使用率可以达到95%.
该过程包含“元素”是我要限制的过程
private static readonly string[] RestrictedProcess = new[] { "element" }; 
    static void ProcessChecker(object o)
    {
        List<Process> resProc = new List<Process>();
        foreach(Process p in Process.GetProcesses())
        {
            string s = p.ProcessName;
            foreach(string rp in RestrictedProcess)
            {
                s = s.ToLower();
                if (s.Contains(rp))
                    resProc.Add(p);
            }
        }

        foreach(Process p in resProc)
        {
            p.PriorityBoostEnabled = false;
            p.PriorityClass = ProcesspriorityClass.Idle;
            p.MaxWorkingSet = new IntPtr(20000000);
        }

        SetPowerConfig(resProc.Count > 0 ? PowerOption.GreenComputing : PowerOption.Balanced);
    }

提前致谢…

解决方法

如果您要限制的程序不是您的程序,则有几个选项:

>将进程优先级设置为空闲,并且不要限制cpu使用率,因为在任何情况下尽可能使用cpu.如果有一些有用的东西,那么让你的cpu运行100%是可行的.如果优先级空闲,则如果另一个程序需要cpu,则该特定进程的cpu使用率将会降低.
>如果您的系统是多核或多cpu,那么您可能需要设置processor affinity.这将告诉您的程序只使用您希望他使用的处理器.例如,如果您的程序是多线程的,并且能够消耗您的两个cpu的100%,则将其亲和力设置为仅使用一个cpu.那么他的使用量将只有50%.
>最差的选项,但实际使用的90%的“cpu限制程序”你会发现在网络上:衡量一个进程的cpu使用情况,并暂停和恢复它定期,直到cpu使用率达到你想要的值.

要暂停/恢复不是您的进程,您必须使用P / Invoke(并且这需要访问该进程,因此,如果您是Windows Vista或更高版本,请关注UAC以获取管理员权限):

/// <summary>
/// The process-specific access rights.
/// </summary>
[Flags]
public enum ProcessAccess : uint
{
    /// <summary>
    /// required to terminate a process using TerminateProcess.
    /// </summary>
    Terminate = 0x1,/// <summary>
    /// required to create a thread.
    /// </summary>
    CreateThread = 0x2,/// <summary>
    /// Undocumented.
    /// </summary>
    SetSessionId = 0x4,/// <summary>
    /// required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).
    /// </summary>
    VmOperation = 0x8,/// <summary>
    /// required to read memory in a process using ReadProcessMemory.
    /// </summary>
    VmRead = 0x10,/// <summary>
    /// required to write to memory in a process using WriteProcessMemory.
    /// </summary>
    VmWrite = 0x20,/// <summary>
    /// required to duplicate a handle using DuplicateHandle.
    /// </summary>
    DupHandle = 0x40,/// <summary>
    /// required to create a process.
    /// </summary>
    CreateProcess = 0x80,/// <summary>
    /// required to set memory limits using SetProcessWorkingSetSize.
    /// </summary>
    SetQuota = 0x100,/// <summary>
    /// required to set certain information about a process,such as its priority class (see SetPriorityClass).
    /// </summary>
    Setinformation = 0x200,/// <summary>
    /// required to retrieve certain information about a process,such as its token,exit code,and priority class (see OpenProcesstoken,GetExitCodeProcess,GetPriorityClass,and IsProcessInJob).
    /// </summary>
    Queryinformation = 0x400,/// <summary>
    /// Undocumented.
    /// </summary>
    SetPort = 0x800,/// <summary>
    /// required to suspend or resume a process.
    /// </summary>
    SuspendResume = 0x800,/// <summary>
    /// required to retrieve certain information about a process (see QueryFullProcessImageName). A handle that has the PROCESS_QUERY_informatION access right is automatically granted PROCESS_QUERY_LIMITED_informatION.
    /// </summary>
    QueryLimitedinformation = 0x1000,/// <summary>
    /// required to wait for the process to terminate using the wait functions.
    /// </summary>
    Synchronize = 0x100000
}

[DllImport("ntdll.dll")]
internal static extern uint NtResumeProcess([In] IntPtr processHandle);

[DllImport("ntdll.dll")]
internal static extern uint NtSuspendProcess([In] IntPtr processHandle);

[DllImport("kernel32.dll",SetLastError = true)]
internal static extern IntPtr OpenProcess(
    ProcessAccess desiredAccess,bool inheritHandle,int processId);

[DllImport("kernel32.dll",SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle([In] IntPtr handle);

public static void SuspendProcess(int processId)
{
    IntPtr hProc = IntPtr.Zero;
    try
    {
        // Gets the handle to the Process
        hProc = OpenProcess(ProcessAccess.SuspendResume,false,processId);

        if (hProc != IntPtr.Zero)
        {
            NtSuspendProcess(hProc);
        }
    }
    finally
    {
        // Don't forget to close handle you created.
        if (hProc != IntPtr.Zero)
        {
            CloseHandle(hProc);
        }
    }
}

C#系统CPU使用率并与Windows任务管理器同步

C#系统CPU使用率并与Windows任务管理器同步

这是一个两部分问题,我想在堆栈上发布我的代码,以帮助其他人完成相同的任务.

问题1:

我有一个代码子集,我相信,根据测量间隔正确地测量cpu使用率(在系统中,根据检索的次数) – 我在线程调用中使用1秒.

我不得不从网上和C代码中的极少数文章中解读这个.我的问题是,对于问题1,这是正确的我做了什么?

有时返回的值是负数,这就是我乘以-1的原因.我再次假设,因为文档很少,这就是我应该做的.

我有以下代码:

public static class Processor
{
    [DllImport("kernel32.dll",SetLastError = true)]
    static extern bool GetSystemTimes(out ComTypes.FILETIME lpIdleTime,out ComTypes.FILETIME lpKernelTime,out ComTypes.FILETIME lpUserTime);

    private static TimeSpan _sysIdleOldTs;
    private static TimeSpan _sysKernelOldTs;
    private static TimeSpan _sysUserOldTs;

    static Processor()
    {
    }

    public static void test()
    {
        ComTypes.FILETIME sysIdle,sysKernel,sysUser;

        if(GetSystemTimes(out sysIdle,out sysKernel,out sysUser))
        {
            TimeSpan sysIdleTs = GetTimeSpanFromFileTime(sysIdle);
            TimeSpan sysKernelTs = GetTimeSpanFromFileTime(sysKernel);
            TimeSpan sysUserTs = GetTimeSpanFromFileTime(sysUser);

            TimeSpan sysIdleDiffenceTs = sysIdleTs.Subtract(_sysIdleOldTs);
            TimeSpan sysKernelDiffenceTs = sysKernelTs.Subtract(_sysKernelOldTs);
            TimeSpan sysUserDiffenceTs = sysUserTs.Subtract(_sysUserOldTs);

            _sysIdleOldTs = sysIdleTs;
            _sysKernelOldTs = sysKernelTs;
            _sysUserOldTs = sysUserTs;

            TimeSpan system = sysKernelDiffenceTs.Add(sysUserDiffenceTs);

            Double cpuUsage = (((system.Subtract(sysIdleDiffenceTs).TotalMilliseconds) * 100) / system.TotalMilliseconds);

            if (cpuUsage < 0)
            {
                Console.WriteLine("cpu: " + ((int) (cpuUsage)*-1) + "%");
            }
            else
            {
                Console.WriteLine("cpu: " + (int) (cpuUsage) + "%");
            }
            Console.WriteLine("");
        }
        else
        {
            Console.WriteLine("Couldn't get cpu usage!");
            Console.WriteLine("");
        }
    }

    private static TimeSpan GetTimeSpanFromFileTime(ComTypes.FILETIME time)
    {
        return TimeSpan.FromMilliseconds((((ulong)time.dwHighDateTime << 32) + (uint)time.dwLowDateTime) * 0.000001);
    }
}

问题2:

在我的程序中,我是否有同步线程与Windows任务管理器的线程,以便匹配测量数据,例如cpu使用率与上述代码?

我的意思是,如果你打开Windows任务管理器,你会注意到它每秒轮询一次 – 实际上它不需要小于那个.我想要做的是将时间与我的线程相匹配.

因此,当Windows任务管理器轮询时,我的线程轮询.

一些说明:

我不想使用性能计数器或.NET内置方法.事实上,我相信 – 从我所读到的,.NET没有计算机器上cpu使用率的方法,否则就需要性能计数器.

性能计数器有开销,此外使GC增长,更不用说调用下一个结果的延迟.虽然我的软件不需要是实时性能,但我确实需要它作为响应并尽可能少地使用cpu时间.上述代码可以在不到一毫秒的时间内调用和返回.实际上在我的开发机器上,时间跨度差异显示为0ms.我不相信性能计数器具有响应性.

如果你很好奇,我的软件收集了许多项目,cpu,内存,事件日志项等,这些项目都需要在sql CE中收集和存储,在下一次轮询之前,1秒钟之后.然而,每个任务,项目都在其自己的线程上以促进这一点.

此外,上面的代码无论如何都没有优化,你会注意到我还没有评论它.原因是我想在优化之前确保它是正确的.

更新1

根据我做出的改进,我删除了额外的“系统”时间跨度,因为它不是必需的,并修改了检索“cpu使用率”并适当地投射它的行.

int cpuUsage = (int)(((sysKernelDifferenceTs.Add(sysUserDifferenceTs).Subtract(sysIdleDifferenceTs).TotalMilliseconds) * 100.00) / sysKernelDifferenceTs.Add(sysUserDifferenceTs).TotalMilliseconds);

虽然我仍然不确定这个公式.虽然它看起来非常准确,但它有时会返回一个负数,这就是为什么我将它乘以-1,如果是这样的话.毕竟,没有这样的事情,cpu使用率为-2%等.

更新2

所以我使用“System.Diagnostics.PerformanceCounter”做了一个简单的测试.虽然非常方便,并且确实完成了它的目的,但确实会产生开销.

以下是我的观察:

>性能计数器的初始化时间要长得多.我的i7 2.6 Ghz大约延长了三秒钟.
>只需使用它,性能计数器似乎还增加了大约5MB的RAM使用量.我的意思是:使用上面的代码,我的应用程序最大内存为7.5MB.凭借性能计数器,它“启动”为12.5MB.
>在5秒的时间内,我的线程运行5次 – 每秒一次,我的应用程序的内存增加了1 MB,这个增加与时间一致,虽然它确实达到了平衡,但在我的情况下,无论如何,3开始时4MB以上.因此,我的应用程序通常使用上面的代码7.5MB内存,PC代码在16.5 MB内存时达到平衡 – 比上面的代码增加了9MB.注意:上面的代码不会导致这种增加.

因此,如果您的应用程序是以资源使用和时间关键的方式构建的,那么我建议不要使用性能计数器,因为这些原因.否则继续前进,因为它没有所有的混乱.

至于我的应用程序,性能计数器将不利于我的软件的目的.

解决方法

我觉得你的公式中有一个错误.您希望基本上计算cpu使用率,如下所示:

cpu Usage = KernelTimeDiff + UserTimeDiff
            --------------------------------------------
            KernelTimeDiff + UserTimeDiff + IdleTimeDiff

因此,快速修改代码如下:

//  TimeSpan system = sysKernelDiffenceTs.Add(sysUserDiffenceTs);
        //Double cpuUsage = (((system.Subtract(sysIdleDiffenceTs).TotalMilliseconds) * 100) / system.TotalMilliseconds); 

        TimeSpan totaltime = sysKernelDiffenceTs.Add(sysUserDiffenceTs);
        totaltime = totaltime.Add(sysIdleDifferenceTs);
        int cpuUsage = 100 - (sysIdleDifferenceTs.TotalMilliseconds * 100) / totaltime.TotalMilliseconds;
       Console.WriteLine("cpu: " + cpuUsage + "%");

您最初将cpuUsage声明为“Double”.我不确定你是否想要浮点精度,但在你的代码中,你肯定没有得到除整数精度之外的任何东西,因为赋值语句只是在进行整数运算.如果你需要更高的计算精度,你可以通过混合一些浮点来轻松获得它:

Double cpuUsage = 100.0 - (sysIdleDifferenceTs.TotalMilliseconds * 100.0) /totaltime.TotalMilliseconds;

此外,关于与任务管理器同步.据我所知,任务管理器使用perf计数器. (而且我怀疑GetSystemTimes正在进行全面反击调用,但可能没有).而且我不确定你为什么不使用perf计数器. “%Process Time”计数器是一个即时样本计数器,不需要计算具有先前结果的差异. (每个逻辑cpu有一个).使用PDH帮助程序函数而不是旧的注册表项apis来获取它.您可以从非托管C/C++ DLL执行此操作,该DLL将“GetcpuUsage”函数导出回您的C#代码.但是我不知道为什么你不能只用P#从P#中调用PDH函数.我不知道你说的这个开销.我不确定我是否理解你提到“延迟调用下一个结果”.

Delphi 获得每个进程的CPU使用率

Delphi 获得每个进程的CPU使用率

function GetCPUUsage(var liOldIdleTime, liOldSystemTime: LARGE_INTEGER): string;
type
  TSystem_Basic_Information = packed record
    dwUnknown1: DWORD;
    uKeMaximumIncrement: ULONG;
    uPageSize: ULONG;
    uMmNumberOfPhysicalPages: ULONG;
    uMmLowestPhysicalPage: ULONG;
    uMmHighestPhysicalPage: ULONG;
    uAllocationGranularity: ULONG;
    pLowestUserAddress: Pointer;
    pMmHighestUserAddress: Pointer;
    uKeActiveProcessors: ULONG;
    bKeNumberProcessors: byte;
    bUnknown2: byte;
    wUnknown3: word;
  end;

  TSystem_Performance_Information = packed record
    liIdleTime: LARGE_INTEGER; {LARGE_INTEGER}
    dwSpare: array[0..75] of DWORD;
  end;

  TSystem_Time_Information = packed record
    liKeBootTime: LARGE_INTEGER;
    liKeSystemTime: LARGE_INTEGER;
    liExpTimeZoneBias: LARGE_INTEGER;
    uCurrentTimeZoneId: ULONG;
    dwReserved: DWORD;
  end;

  TNtQuerySystemInformation = function(infoClass: DWORD; buffer: Pointer; bufSize: DWORD; var returnSize: Dword): DWORD; stdcall;
var
  NtQuerySystemInformation: TNtQuerySystemInformation;
  SysBaseInfo: TSystem_Basic_Information;
  SysPerfInfo: TSystem_Performance_Information;
  SysTimeInfo: TSystem_Time_Information;
  status: DWORD; {long}
  dbSystemTime: Double;
  dbIdleTime: Double;
begin
  Result := ''<N/A>'';

  NtQuerySystemInformation := GetProcAddress(GetModuleHandle(''ntdll.dll''), ''NtQuerySystemInformation'');
  if @NtQuerySystemInformation = nil then Exit;
  
  if (NtQuerySystemInformation(0, @SysBaseInfo, SizeOf(SysBaseInfo), status) <> 0)
    or (NtQuerySystemInformation(3, @SysTimeInfo, SizeOf(SysTimeInfo), status) <> 0)
    or (NtQuerySystemInformation(2, @SysPerfInfo, SizeOf(SysPerfInfo), status) <> 0) then Exit;

  if liOldIdleTime.QuadPart <> 0 then
  begin
    // CurrentValue = NewValue - OldValue
    dbIdleTime := Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
    dbSystemTime := Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);

    // CurrentCpuIdle = IdleTime / SystemTime
    dbIdleTime := dbIdleTime / dbSystemTime;

    // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
    dbIdleTime := 100.0 - dbIdleTime * 100.0 / SysBaseInfo.bKeNumberProcessors{ + 0.5};

    // Show Percentage
    Result := FormatFloat(''0.00 %'',dbIdleTime);
  end;
  liOldIdleTime := SysPerfInfo.liIdleTime;
  liOldSystemTime := SysTimeInfo.liKeSystemTime;
end;


今天关于计算Windows进程的CPU使用率?windows进程cpu占用100%的讲解已经结束,谢谢您的阅读,如果想了解更多关于c – 如何在Windows上限制进程的CPU使用率?、c# – 如何限制进程的CPU使用率、C#系统CPU使用率并与Windows任务管理器同步、Delphi 获得每个进程的CPU使用率的相关知识,请在本站搜索。

本文标签: