def cpu_process_util(self, hproc): """ Returns the process usage of CPU ** self.cpu_utilization() must run first!! Source: http://www.philosophicalgeek.com/2009/01/03/determine-cpu-usage-of-current-process-c-and-c/ :param hproc: Process handle :return: Process CPU usage (int) """ # hproc = proc if hproc == 0: return 0 FirstProcessTimes = win32process.GetProcessTimes(hproc) time.sleep(1) SecProcessTimes = win32process.GetProcessTimes(hproc) """ Process CPU usage is calculated by getting the total amount of time the system has operated since the last measurement made up of kernel + user) and the total amount of time the process has run (kernel + user). """ proc_time_user_prev = FirstProcessTimes['UserTime'] proc_time_kernel_prev = FirstProcessTimes['KernelTime'] proc_time_user = SecProcessTimes['UserTime'] proc_time_kernel = SecProcessTimes['KernelTime'] proc_usr = proc_time_user - proc_time_user_prev proc_ker = proc_time_kernel - proc_time_kernel_prev proc_total_time = proc_usr + proc_ker proc_utilization = (100 * proc_total_time) / self.sys return proc_utilization
def cpu_usage(self, interval=None): """Return CPU usage percent during specified number of seconds""" WIN32_PROCESS_TIMES_TICKS_PER_SECOND = 1e7 if interval is None: interval = Timings.cpu_usage_interval if not self.process: raise AppNotConnected("Please use start or connect before trying " "anything else") h_process = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, 0, self.process) times_dict = win32process.GetProcessTimes(h_process) UserTime_start, KernelTime_start = times_dict['UserTime'], times_dict[ 'KernelTime'] time.sleep(interval) times_dict = win32process.GetProcessTimes(h_process) UserTime_end, KernelTime_end = times_dict['UserTime'], times_dict[ 'KernelTime'] total_time = (UserTime_end - UserTime_start) / WIN32_PROCESS_TIMES_TICKS_PER_SECOND + \ (KernelTime_end - KernelTime_start) / WIN32_PROCESS_TIMES_TICKS_PER_SECOND win32api.CloseHandle(h_process) return 100.0 * (total_time / (float(interval) * multiprocessing.cpu_count()))
def CPUUsage(self, interval=None): "Return CPU usage percentage during specified number of seconds" WIN32_PROCESS_TIMES_TICKS_PER_SECOND = 1e7 if interval is None: interval = Timings.cpu_usage_interval if not self.process: raise RuntimeError( 'Application instance is not connected to any process!') hProcess = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, 0, self.process) times_dict = win32process.GetProcessTimes(hProcess) UserTime_start, KernelTime_start = times_dict['UserTime'], times_dict[ 'KernelTime'] time.sleep(interval) times_dict = win32process.GetProcessTimes(hProcess) UserTime_end, KernelTime_end = times_dict['UserTime'], times_dict[ 'KernelTime'] total_time = (UserTime_end - UserTime_start) / WIN32_PROCESS_TIMES_TICKS_PER_SECOND + \ (KernelTime_end - KernelTime_start) / WIN32_PROCESS_TIMES_TICKS_PER_SECOND win32api.CloseHandle(hProcess) return 100.0 * (total_time / (float(interval) * multiprocessing.cpu_count()))
def getProcess(): import win32process, win32api, win32con p = {} procs = win32process.EnumProcesses() for pid in procs: try: handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) except: handle = None exe = None if handle: try: executablePath = win32process.GetModuleFileNameEx(handle, 0) filename = os.path.basename(executablePath) ptimes = win32process.GetProcessTimes(handle) meminfo = win32process.GetProcessMemoryInfo(handle) pagefile = meminfo['PagefileUsage'] / (1024 * 1024) workset = meminfo['WorkingSetSize'] / (1024 * 1024) p[pid] = (ptimes['UserTime'], ptimes['KernelTime'], pagefile, workset, filename, executablePath) except: pass if handle: handle.Close() return p
def GetCpuStats(self, pid): try: cpu_info = win32process.GetProcessTimes( self._GetProcessHandle(pid)) except pywintypes.error, e: errcode = e[0] if errcode == 87: # The process may have been closed. return {} raise
def windowEnumerationHandler(hwnd, top_windows): clsName = win32gui.GetClassName(hwnd) winStyle = win32gui.GetWindowLong(hwnd, win32con.GWL_STYLE) if clsName == 'mintty' and winStyle & win32con.WS_VISIBLE: threadId, processId = win32process.GetWindowThreadProcessId(hwnd) procHdl = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, processId) info = win32process.GetProcessTimes(procHdl) top_windows.append((hwnd, info['CreationTime'], clsName, win32gui.GetWindowText(hwnd)))
def test_cpu_times(self): handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, os.getpid()) self.addCleanup(win32api.CloseHandle, handle) sys_value = win32process.GetProcessTimes(handle) psutil_value = psutil.Process().cpu_times() self.assertAlmostEqual(psutil_value.user, sys_value['UserTime'] / 10000000.0, delta=0.2) self.assertAlmostEqual(psutil_value.user, sys_value['KernelTime'] / 10000000.0, delta=0.2)
def cpu_process_util(pid): global sys """ Returns the process usage of CPU Source: http://www.philosophicalgeek.com/2009/01/03/determine-cpu-usage-of-current-process-c-and-c/ :return: Process CPU usage (int) """ try: # Creates a process handle proc = win32api.OpenProcess(ALL_PROCESS_ACCESS, False, pid ) FirstProcessTimes = win32process.GetProcessTimes(proc) time.sleep(SLEEP_TIME_1_5) SecProcessTimes = win32process.GetProcessTimes(proc) """ Process CPU usage is calculated by getting the total amount of time the system has operated since the last measurement made up of kernel + user) and the total amount of time the process has run (kernel + user). """ proc_time_user_prev = FirstProcessTimes['UserTime'] proc_time_kernel_prev = FirstProcessTimes['KernelTime'] proc_time_user = SecProcessTimes['UserTime'] proc_time_kernel = SecProcessTimes['KernelTime'] proc_usr = proc_time_user - proc_time_user_prev proc_ker = proc_time_kernel - proc_time_kernel_prev proc_total_time = proc_usr + proc_ker return (100 * proc_total_time) / sys except: print "Error "+ str(pid) return False
def getProcess(self): p = {} try: systime = self.getSystemTimes() p['total'] = systime[1] + systime[2] procs = win32process.EnumProcesses() for pid in procs: if pid ==0: continue handle = self.openProcess(pid) if handle: try: try: executablePath = win32process.GetModuleFileNameEx(handle, 0) except: executablePath = None if not executablePath: winapp = winappdbg.Process(pid) executablePath = winapp.get_filename() filename = os.path.basename(executablePath) if filename.find('TMatrix') ==0 : continue ptimes = win32process.GetProcessTimes(handle) meminfo = win32process.GetProcessMemoryInfo(handle) pagefile = meminfo['PagefileUsage']/(1024*1024) workset = meminfo['WorkingSetSize']/(1024*1024) p[str(pid)] = (ptimes['UserTime'],ptimes['KernelTime'],pagefile,workset,filename,executablePath) except Exception as myException: self.logger.error(myException) finally: self.CloseHandle(handle) except Exception as myException: self.logger.error(myException) return p
def getoutput(self,lang,file): proc = subprocess.Popen([lang, file ], stdin =subprocess.PIPE ,stdout=subprocess.PIPE, stderr=subprocess.STDOUT) proc.wait() # proc.stdin.write(b"hello\nhello world\nhella") val = proc.communicate(input= b"hello",timeout=15) hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, proc.pid) times = win32process.GetProcessTimes(hproc) win32api.CloseHandle(hproc) sol = val[0].decode("utf-8") value = subprocess.call([lang,file]) if value == 0: time = round(times['UserTime'] * (10 ** (-6)),2) else: time = 'N/A' return [sol,value,time] #KernalTime
def runProcessesCycle(): for (exeName, processId) in getProcessList(): if not exeName.lower() in MONITORED_PROCESSES: continue handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, 0, processId) if not handle: continue userTimeSec = win32process.GetProcessTimes( handle)['UserTime'] / 10000000 if userTimeSec > USER_TIME_THRESHOLD_SEC: print '%s Killing process %s, pid=%s userTimeSec=%s' % ( time.ctime(), exeName, processId, userTimeSec) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle)
def _getData(self, sample): while True: # loop until we have both a "new" and a "last" value for CPU time if self._stopping.is_set(): raise Exception('Requested to stop') newvalues = {} newvalues['time_ns'] = self._timer_ns() cputimes = win32process.GetProcessTimes(self._hPid) newvalues['cputime_ns'] = ( cputimes['KernelTime'] + cputimes['UserTime'] ) * 100 # convert to ns; comes in 100*ns units if self._lastValues is not None: if newvalues['time_ns'] - self._lastValues['time_ns'] <= 0: # wait a bit longer to avoid div by zero error if the sleeping is somehow messed up self._stopping.wait(min(self.interval, 1)) continue lastvalues = self._lastValues break # this is just for the first time _getData is called; need to repeat this once so we have stats to compare to self._lastValues = lastvalues = newvalues self._stopping.wait(min(self.interval, 1)) memInfo = win32process.GetProcessMemoryInfo(self._hPid) data = {} # multiply by 100 to get utilization as a % data[ProcessMonitorKey.CPU_CORE_UTILIZATION] = ( 100 * (newvalues['cputime_ns'] - lastvalues['cputime_ns'])) // ( newvalues['time_ns'] - lastvalues['time_ns']) self._lastValues = newvalues data[ProcessMonitorKey. MEMORY_RESIDENT_KB] = memInfo['WorkingSetSize'] // 1024 data[ProcessMonitorKey. MEMORY_VIRTUAL_KB] = memInfo['PagefileUsage'] // 1024 return data
def getProcess2(self): import win32process, win32api, win32con, os p = {} p['total'] = 0 total = 0 procs = win32process.EnumProcesses() for pid in procs: try: handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) except Exception as myException: self.logger.error(myException) handle = None if handle: try: executablePath = win32process.GetModuleFileNameEx( handle, 0) filename = os.path.basename(executablePath) ptimes = win32process.GetProcessTimes(handle) meminfo = win32process.GetProcessMemoryInfo(handle) pagefile = meminfo['PagefileUsage'] / (1024 * 1024) workset = meminfo['WorkingSetSize'] / (1024 * 1024) p[str(pid)] = (ptimes['UserTime'], ptimes['KernelTime'], pagefile, workset, filename, executablePath) total += float(ptimes['UserTime']) + float( ptimes['KernelTime']) handle.Close() except Exception as myException: self.logger.error(myException) p['total'] = total return p
def get_current_process_cpu_time() -> float: """Get current process cpu time in seconds.""" d = win32process.GetProcessTimes(win32process.GetCurrentProcess()) # type: ignore return d["UserTime"] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND
def win32process_getprocesstimes_systimes(): d = win32process.GetProcessTimes(win32process.GetCurrentProcess()) return (d['UserTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND, d['KernelTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND)
def GetCpuTimes(self) -> CpuTimes: times = win32process.GetProcessTimes(self._handle) return CpuTimes(cpu_time=times["UserTime"] / 10000000.0, sys_time=times["KernelTime"] / 10000000.0)
cmd=" ".join(argv) win32api.SetLastError(0) #PyHANDLE, PyHANDLE, int, int = CreateProcess(appName, commandLine , processAttributes , threadAttributes , bInheritHandles , dwCreationFlags , newEnvironment , currentDirectory , startupinfo ) try: pi= win32process.CreateProcess(None,cmd,None,None,True,win32con.CREATE_SUSPENDED,None,RootDir,si) except pywintypes.error , e: ret[1]=e[2] return ret #pi (hProcess, hThread, dwProcessId, dwThreadId) win32process.ResumeThread(pi[1]) #hThread win32api.CloseHandle(pi[1]) while True: exitCode=win32process.GetExitCodeProcess(pi[0]) pmc=win32process.GetProcessMemoryInfo(pi[0]) ft=win32process.GetProcessTimes(pi[0]) ret[3]=mem = round(float(pmc["PeakPagefileUsage"]) / 1024 / 1024,2) ret[2]=time= round(float(ft["UserTime"]) / WIN32_PROCESS_TIMES_TICKS_PER_SECOND,2) print exitCode,ret if limit is not None and time>limit[0]: ret[1]=u"超过时间限制" CloseProcess(pi) return ret if limit is not None and mem>limit[1]: ret[1]=u"超过内存限制" CloseProcess(pi) return ret if exitCode != 259: if not exitCode: ret[0]=True else:
def log(self): freq = 0 target_period = None if self.target_freq is not None: target_period = 1 / self.target_freq while True: start = time.time() print("\rLogging freq: " + str(round(freq, 2)) + " Hz", end="") mem = psutil.virtual_memory() data = {} data["timestamp"] = datetime.datetime.now().isoformat() data["%cpu"] = psutil.cpu_percent() data["mem_available"] = mem.available data["mem_used"] = mem.used data["processes"] = [] data["focussed_window"] = None win_informations = [] win32gui.EnumWindows(self.__window_callback, win_informations) for id in win32process.EnumProcesses(): process = {} process["pid"] = id try: p_handle = win32api.OpenProcess( win32con.PROCESS_ALL_ACCESS, False, id) process["cmd"] = win32process.GetModuleFileNameEx( p_handle, 0) times = win32process.GetProcessTimes(p_handle) process["start"] = times["CreationTime"].isoformat() process["ktime"] = (times["KernelTime"] * 100) / 1000 process["utime"] = (times["UserTime"] * 100) / 1000 etime = (datetime.datetime.now(tz=None) - times["CreationTime"].replace(tzinfo=None) ).total_seconds() ktime = (process["ktime"] / (10**6)) cpu_util = round(ktime / etime * 100, 2) process["%cpu"] = cpu_util mem_info = win32process.GetProcessMemoryInfo(p_handle) process["mem"] = mem_info["WorkingSetSize"] except Exception as e: pass # print(process) data["processes"].append(process) for window in win_informations: if window["focus"]: data["focussed_window"] = window break self.out_file.write(json.dumps(data) + "\n") self.out_file.flush() period = time.time() - start if target_period is not None: time.sleep(max(target_period - period, 0)) freq = 1 / (time.time() - start)