找回密码  加入

QQ登录

只需一步,快速开始

AUTOIT CN

搜索
查看: 1523|回复: 4

[效率算法] 关于单个进程的cpu使用率问题=已解决

[复制链接]
发表于 2017-6-26 21:34:27 | 显示全部楼层 |阅读模式
本帖最后由 a000000 于 2017-6-29 00:10 编辑

单个进程的cpu使用率超过百分之90自动关闭该程序

可是遇到一个问题:获取不准确,比如某个程序启动,看任务管理器最高cpu30%
可是本程序检测到百分97-100%,会立即关闭进程,请教下如何处理,
请大侠帮忙

附带源码如下:

  1. #include <WindowsConstants.au3>

  2. Opt('MustDeclareVars', 1)
  3. Opt("TrayIconHide", 1)
  4. HotKeySet("{ESC}", "_Exit")

  5. Global Const $Process_All_Access = 0x1F0FFF
  6. Global $CreateTime = DllStructCreate("dword;dword")
  7. Global $ExitTime = DllStructCreate("dword;dword")
  8. Global $KernelTime = DllStructCreate("dword;dword")
  9. Global $UserTime = DllStructCreate("dword;dword")
  10. Global $FileTime = DllStructCreate("dword;dword")
  11. Global $SystemTime = DllStructCreate("ushort;ushort;ushort;ushort;ushort;ushort;ushort;ushort")
  12. Global $IdleTime = DllStructCreate("dword;dword")
  13. Global $sUserTime, $sKernelTime, $eUserTime, $eKernelTime
  14. Global $ret, $hour, $minutes, $seconds, $milliseconds
  15. Global $ProcHandle, $Process_CPU_Usage
  16. Global $PID, $CPUTime, $mem, $prg
  17. Global $logical_cpus = CPU()
  18. Global $hProc
  19. Global $GUI, $info

  20. ;~ ======================================================================
  21. $prg = "ORTHOS.exe"

  22. ;~ Run($prg)
  23. Sleep(500)

  24. $PID = ProcessExists($prg)
  25. If $PID = 0 Then
  26.     ConsoleWrite(@CRLF & "ERROR! Process " & $prg & " not found! Aborting..." & @CRLF)
  27.     Exit
  28. EndIf

  29. Global $iMemo, $hDebugGUI
  30. $GUI = GUICreate("Process Information - Press ESC to quit!",  300, 25, -1, -1, BitOR($WS_CAPTION,$WS_POPUP,$WS_BORDER,$WS_CLIPSIBLINGS))
  31. $iMemo = GUICtrlCreateEdit("", -1, -1, 820)
  32. GUICtrlSetFont($iMemo, 9, 400, 0, "Courier New")
  33. GUICtrlSetBkColor($iMemo, 0xFFFFFF)
  34. GUISetState()

  35. $ProcHandle = DllCall("kernel32.dll", "hwnd", "OpenProcess", "dword", $Process_All_Access, "int", False, "dword", $PID)
  36. $ProcHandle = $ProcHandle[0]

  37. While 1
  38.     _GetProcTime($ProcHandle)
  39.        
  40.         If $Process_CPU_Usage > 90 Then ProcessClose ( $PID )
  41. ;~         =========================================================================================================
  42.         $info =  @CR & $prg & " | PID: " & $PID & " | CPU usage: " & $Process_CPU_Usage & " % " & @CR
  43.     MemoWrite($info)
  44.     Sleep(1000)
  45.     If Not ProcessExists($PID) Then _Exit()
  46. WEnd


  47. Func MemoWrite($sMessage = "")
  48.     GUICtrlSetData($iMemo, $sMessage)
  49. EndFunc ;==>MemoWrite

  50. Func _GetProcTime($ProcessHandle)
  51.     $ret = DllCall("kernel32.dll", "int", "GetProcessTimes", "int", $ProcessHandle, "ptr", DllStructGetPtr($CreateTime), "ptr", DllStructGetPtr($ExitTime), "ptr", DllStructGetPtr($KernelTime), "ptr", DllStructGetPtr($UserTime))
  52.     If $ret[0] = 0 Then
  53.     ConsoleWrite("(" & @ScriptLineNumber & ") : = Error in GetProcessTimes call" & @CRLF)
  54.     SetError(1, 0, $ret[0])
  55.     EndIf
  56.     $sKernelTime = DllStructGetData($KernelTime, 1)
  57.     $sUserTime = DllStructGetData($UserTime, 1)
  58.     $Process_CPU_Usage = Floor(($sKernelTime - $eKernelTime + $sUserTime - $eUserTime) / 100000 / $logical_cpus)
  59.     If $Process_CPU_Usage > 100 Then $Process_CPU_Usage = "100"
  60.     $eKernelTime = $sKernelTime
  61.     $eUserTime = $sUserTime
  62.     Return $sUserTime + $sKernelTime
  63. EndFunc ;==>_GetProcTime

  64. Func _ProcessGetMem($ProcessHandle) ;get physical memory of the process -> http://msdn.microsoft.com/en-us/library/ms683219%28VS.85%29.aspx
  65.     Local $structPROCESS_MEMORY_COUNTERS, $structPROCESS_MEMORY_COUNTERS_EX, $nSize, $aRet
  66.     If @OSVersion <> "WIN_7" Then
  67.     $structPROCESS_MEMORY_COUNTERS = DllStructCreate("dword cb; dword PageFaultCount; uint PeakWorkingSetSize; uint WorkingSetSize; " & _
  68.     "uint QuotaPeakPagedPoolUsage; uint QuotaPagedPoolUsage; uint QuotaPeakNonPagedPoolUsage; " & _
  69.     "uint QuotaNonPagePoolUsage; uint PagefileUsage; uint PeakPagefileUsage") ;http://msdn.microsoft.com/en-us/library/ms684877%28VS.85%29.aspx
  70.     $nSize = DllStructGetSize($structPROCESS_MEMORY_COUNTERS)
  71.     $aRet = DllCall("psapi.dll", "int", "GetProcessMemoryInfo", "hwnd", $ProcessHandle, "ptr", DllStructGetPtr($structPROCESS_MEMORY_COUNTERS), "dword", $nSize) ;call GetProcessMemoryInfo
  72.     If $aRet[0] = 0 Then
  73.     ConsoleWrite("(" & @ScriptLineNumber & ") : = Error in GetProcessMemoryInfo call" & @LF)
  74.     SetError(1, 0, $aRet[0])
  75.     EndIf
  76.     Return DllStructGetData($structPROCESS_MEMORY_COUNTERS, "WorkingSetSize")
  77.     Else
  78.     $structPROCESS_MEMORY_COUNTERS_EX = DllStructCreate("dword cb; dword PageFaultCount; uint PeakWorkingSetSize; uint WorkingSetSize; " & _
  79.     "uint QuotaPeakPagedPoolUsage; uint QuotaPagedPoolUsage; uint QuotaPeakNonPagedPoolUsage; " & _
  80.     "uint QuotaNonPagePoolUsage; uint PagefileUsage; uint PeakPagefileUsage; " & _
  81.     "uint PrivateUsage") ;http://msdn.microsoft.com/en-us/library/ms684877%28VS.85%29.aspx
  82.     $nSize = DllStructGetSize($structPROCESS_MEMORY_COUNTERS_EX)
  83.     $aRet = DllCall("Kernel32.dll", "int", "K32GetProcessMemoryInfo", "hwnd", $ProcessHandle, "ptr", DllStructGetPtr($structPROCESS_MEMORY_COUNTERS_EX), "dword", $nSize) ;call GetProcessMemoryInfo
  84.     If $aRet[0] = 0 Then
  85.     ConsoleWrite("(" & @ScriptLineNumber & ") : = Error in GetProcessMemoryInfo call" & @LF)
  86.     SetError(1, 0, $aRet[0])
  87.     EndIf
  88. ;~  ConsoleWrite("WorkingSetSize: " & Round(DllStructGetData($structPROCESS_MEMORY_COUNTERS_EX, "WorkingSetSize") / 1024, 0) & @CRLF & _
  89. ;~  "PrivateUsage: " & Round(DllStructGetData($structPROCESS_MEMORY_COUNTERS_EX, "PrivateUsage") / 1024, 0) & @CRLF & @CRLF)
  90.     Return DllStructGetData($structPROCESS_MEMORY_COUNTERS_EX, "PrivateUsage")
  91.     EndIf
  92. EndFunc ;==>_ProcessGetMem

  93. Func CPU() ;get logical CPU(s)
  94.     Local $i, $j, $x, $os, $colItems, $HW_Processor_Description, $HW_Processor_Manufacturer, $HW_Processor_MaxClockSpeed, $HW_Processor_Name, $HW_Processor_SocketDesignation
  95.     Local $system = "Localhost"
  96.     Local $objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate}!\" & $system & "\root\cimv2")

  97.     $colItems = $objWMIService.ExecQuery("SELECT Caption from Win32_OperatingSystem", "WQL", 0x30) ;get OS version
  98.     If IsObj($colItems) Then
  99.     For $objItem In $colItems
  100.     $os = $objItem.Caption
  101.     Next
  102.     EndIf
  103.     If StringInStr($os, "2003") > 0 Or StringInStr($os, "2000") > 0 Or StringInStr(StringUpper($os), "XP") > 0 Then
  104.     $colItems = $objWMIService.ExecQuery("Select Name, Description, Manufacturer, MaxClockSpeed, SocketDesignation from Win32_Processor", "WQL", 0x30)
  105.     Else
  106.     $colItems = $objWMIService.ExecQuery("Select Name, Description, Manufacturer, MaxClockSpeed, SocketDesignation, NumberOfCores, NumberOfLogicalProcessors from Win32_Processor", "WQL", 0x30)
  107.     EndIf
  108.     If IsObj($colItems) Then
  109.     $i = 0
  110.     $j = 0
  111.     $HW_Processor_SocketDesignation = ""
  112.     For $objItem In $colItems ;get amount of logical CPUs
  113.     If StringInStr(StringLower($HW_Processor_SocketDesignation), StringLower($objItem.SocketDesignation)) = 0 Then
  114.     $HW_Processor_SocketDesignation &= $objItem.SocketDesignation & ", "
  115.     EndIf
  116.     $i = $i + 1
  117.     Next
  118.     If StringInStr($os, "2003") > 0 Or StringInStr($os, "2000") > 0 Or StringInStr(StringUpper($os), "XP") > 0 Then
  119.     $x = StringSplit(Remove_Last_Comma($HW_Processor_SocketDesignation), ",")
  120.     $j = UBound($x) - 1
  121.     Else
  122.     $i = $objItem.NumberOfCores
  123.     $j = $objItem.NumberOfLogicalProcessors / $i
  124.     EndIf
  125.     If $j > $i Then $j = $i
  126.     EndIf
  127.     Return ($i)
  128. EndFunc ;==>CPU

  129. Func Remove_Last_Comma($str)
  130.     If StringRight($str, 2) = ", " Then $str = StringMid($str, 1, StringLen($str) - 2)
  131.     Return $str
  132. EndFunc ;==>Remove_Last_Comma

  133. Func _Exit()
  134.     DllCall("kernel32.dll", "int", "CloseHandle", "int", $ProcHandle)
  135.     DllCall("psapi.dll", "int", "CloseHandle", "hwnd", $ProcHandle)
  136. ;~     ProcessClose($pid)
  137.     Exit
  138. EndFunc ;==>_Exit
复制代码
发表于 2017-6-28 08:38:24 | 显示全部楼层
回复 4# lin6051



指定单进程的 cpu占用率
#include <_PDH_ProcessCounters.au3>

Global $bHotKeyPressed=False

Func _EscPressed()
    $bHotKeyPressed=True
EndFunc

;   --------------------    MAIN PROGRAM CODE   --------------------

HotKeySet("{Esc}", "_EscPressed")

_PDH_Init()
Local $poCounter,$hSplash,$sProcess,$iProcessID
Local $iCounterValue,$sSplashText,$iTemp

$sProcess="QQ.exe"     ;进程名; change to "autoit3_x64.exe" for 64-bit process :)
$iProcessID=3608      ;进程ID


$poCounter=_PDH_ProcessObjectCreate($sProcess,$iProcessID)
_PDH_ProcessObjectAddCounters($poCounter,6) ; "% Processor Time"

; successful? Then enter loop
If @error=0 And IsArray($poCounter) Then
    $iCounterValue=Round(_PDH_ProcessObjectUpdateCounters($poCounter,0)/$_PDH_iCPUCount)
    $sSplashText="Process '"&$sProcess&"' (PID #"&$iProcessID&")"&@CRLF&"CPU Usage:"&$iCounterValue&" %"&@CRLF&"[Esc] exits"
    $hSplash=SplashTextOn("Process Info",$sSplashText,360,100,Default,Default,16)
    Do
        Sleep(200)
        $iCounterValue=_PDH_ProcessObjectUpdateCounters($poCounter,0)
        If @error=32 Then ExitLoop      ; Process can no longer be found
        $iCounterValue=Round($iCounterValue/$_PDH_iCPUCount)
        $sSplashText="Process '"&$sProcess&"' (PID #"&$iProcessID&")"&@CRLF&"CPU Usage:"&$iCounterValue&" %"&@CRLF&"[Esc] exits"
        ControlSetText($hSplash,"","[CLASS:Static; INSTANCE:1]",$sSplashText)
    Until $bHotKeyPressed
EndIf
_PDH_ProcessObjectDestroy($poCounter)
_PDH_UnInit()

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?加入

x
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2017-6-27 14:43:16 | 显示全部楼层
顶一下,希望大神帮忙
 楼主| 发表于 2017-6-27 14:43:17 | 显示全部楼层
顶一下,希望大神帮忙
发表于 2017-6-28 08:30:19 | 显示全部楼层
回复 1# a000000


    没有 除 多核吧

有 个udf

#include <_PDH_ProcessCounters.au3>
您需要登录后才可以回帖 登录 | 加入

本版积分规则

QQ|小黑屋|手机版|AUTOIT CN ( 鲁ICP备19019924号-1 )谷歌 百度

GMT+8, 2020-1-25 22:02 , Processed in 0.078125 second(s), 24 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表