Page 1 of 1

[Windows] Two tips to determine high CPU use

Posted: Wed Dec 18, 2013 10:28 am
by PB
For Windows only.

Two procedures to determine an app's CPU use ("none" or "high" only).
Basically just wrappers for "IsHungAppWindow" but in a nice useful way.

You can test the procedures by compiling the first code to an exe
and running it, then calling the procedures with its handle (hWnd).

Code: Select all

; Creates a high-CPU test executable.

OpenWindow(0,200,200,200,100,"CPU High")
Repeat : a+1 : ForEver

Code: Select all

; IsHighCPU() by PB.

; Returns -1 if window not found, or state can't be checked.
; Returns 0  if the window is not hung, or not CPU-intensive.
; Returns 1  if the window is hung, or is CPU-intensive.

Procedure IsHighCPU(hWnd)
  state=-1
  If IsWindow_(hWnd)
    user32=OpenLibrary(#PB_Any,"user32.dll")
    If user32
      If GetFunction(user32,"IsHungAppWindow")
        state=CallFunction(user32,"IsHungAppWindow",hWnd)
      EndIf
      CloseLibrary(user32)
    EndIf
  EndIf
  ProcedureReturn state
EndProcedure

Code: Select all

; WaitForReleasedCPU() by PB.

; Waits for a window's process to release the CPU.
; Checks the status twice a second until it's released,
; or until a timeout threshold (in milliseconds) is reached.

; Returns -1 if window not found, or can't be checked.
; Returns 1  when the window's process releases the CPU.
; Returns 0  if the timeout is reached (CPU not released).

Procedure WaitForReleasedCPU(hWnd,timeout=0)
  status=-1
  If IsWindow_(hWnd)
    user32=OpenLibrary(#PB_Any,"user32.dll")
    If user32
      If GetFunction(user32,"IsHungAppWindow")
        abort=GetTickCount_()+timeout
        Repeat
          Sleep_(500) ; Don't hog the CPU ourselves! :)
          inuse=CallFunction(user32,"IsHungAppWindow",hWnd)
        Until inuse=0 Or GetTickCount_()>abort
        If inuse=0 : status=1 : Else : status=0 : EndIf
      EndIf
      CloseLibrary(user32)
    EndIf
  EndIf
  ProcedureReturn status
EndProcedure