473,785 Members | 2,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trying to find a simple way of getting a Process current CPU Usage

10 New Member
Hi all
I have been looking around the web
and can't seem to find a solution the solution that i have found and manipulated seems to bring back the whole list of currently running process's which hogs a lot of CPU time in its self..

basic idea of my program is i have multiple threads doing things and i have a thread that gathers data within this thread i can currently get all sorts of information using
Expand|Select|Wrap|Line Numbers
  1. b=str(gatherIt("firefox","Working Set"))
  2.  
  3. def gatherIt(whoIt,whatIt):
  4.     #this is the data gathering function thing
  5.     data = win32pdhutil.FindPerformanceAttributesByName(whoIt, counter=whatIt)
  6.     return data
  7.  
this then runs every 10 seconds and out puts the information along with a load of other data into a CSV file.
what i can't seem to do is get the cpu usage of a process.
the process i have found is this
Expand|Select|Wrap|Line Numbers
  1. import time
  2. import wmi,win32api,win32process
  3.  
  4.  
  5. c = wmi.WMI ()
  6. d=win32process.GetProcessTimes(1)
  7. print d
  8. process_info = {}
  9. while True:
  10.   for process in c.Win32_Process ():
  11.     if process.Caption == 'firefox.exe':
  12.       id = process.ProcessID
  13.       for p in c.Win32_PerfRawData_PerfProc_Process (IDProcess=id):
  14.         n1, d1 = long (p.PercentProcessorTime), long(p.Timestamp_Sys100NS)
  15.         n0, d0 = process_info.get (id, (0, 0))
  16.  
  17.       try:
  18.         percent_processor_time = (float (n1 - n0) / float (d1 - d0)) *100.0
  19.       except ZeroDivisionError:
  20.         percent_processor_time = 0.0
  21.       process_info[id] = (n1, d1)
  22.  
  23.       #if percent_processor_time > 0.01:
  24.       print process.Caption, percent_processor_time
  25.  
  26.     print
  27.   time.sleep (5)
  28.  
this seems to take ages to get a result and and if i limit it to that single process it prints out the information as if it was ignoring but still gathering the other process's information and it takes 50% CPU usage... not good
there must be a simpler way to get a single process's cpu usage
please help
Jan 9 '08 #1
3 5927
dittytwo
10 New Member
Hi all
i have managed to fix the 50% thing
bad coding had a while loop checking for the existence of something and no pause.. = loads of CPU resource.
i still need the %cpu-usage for a process any help would be great
Jan 10 '08 #2
dittytwo
10 New Member
Ok
I solved my own problem with a little help from SC (cheers Si)
worst thing is he doesn't even understand python... oh well here is the answer to get a process's CPU usage
Expand|Select|Wrap|Line Numbers
  1. import wmi,win32api,win32process
  2. c = wmi.WMI ()
  3. process_info = {}
  4.   for p in c.Win32_PerfRawData_PerfProc_Process (name='firefox'):
  5.     n1, d1 = long (p.PercentProcessorTime), long(p.Timestamp_Sys100NS)
  6.     n0, d0 = process_info.get (id, (0, 0))
  7.     try:
  8.       percent_processor_time = (float (n1 - n0) / float (d1 - d0)) *100.0
  9.     except ZeroDivisionError:
  10.       percent_processor_time = 0.0
  11.     process_info[id] = (n1, d1)
  12.     print p.Caption, percent_processor_time
  13.  
(NOTE: that you don't have to have the .exe at the end

simple really
I hope this helps someone else (this will be added to ASPN's python cook book.

cheers
D2
Jan 11 '08 #3
bvdet
2,851 Recognized Expert Moderator Specialist
Ok
I solved my own problem with a little help from SC (cheers Si)
worst thing is he doesn't even understand python... oh well here is the answer to get a process's CPU usage
Expand|Select|Wrap|Line Numbers
  1. import wmi,win32api,win32process
  2. c = wmi.WMI ()
  3. process_info = {}
  4.   for p in c.Win32_PerfRawData_PerfProc_Process (name='firefox'):
  5.     n1, d1 = long (p.PercentProcessorTime), long(p.Timestamp_Sys100NS)
  6.     n0, d0 = process_info.get (id, (0, 0))
  7.     try:
  8.       percent_processor_time = (float (n1 - n0) / float (d1 - d0)) *100.0
  9.     except ZeroDivisionError:
  10.       percent_processor_time = 0.0
  11.     process_info[id] = (n1, d1)
  12.     print p.Caption, percent_processor_time
  13.  
(NOTE: that you don't have to have the .exe at the end

simple really
I hope this helps someone else (this will be added to ASPN's python cook book.

cheers
D2
Thanks for sharing this with the Forum. I wish I could have helped, but I know little about interfacing with the operating system.
Jan 11 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

7
6505
by: Joshua Beall | last post by:
Hi All, I am doing some work where I want to do locking, and prevent scripts from running in parallel. I see that I could use the semaphore mechanism, but I'd like for my code to be portable, and that extension is not enabled in many places. I need some way for a process to uniquely identify itself. It can then look at the storage container (flat file, DB, whatever is appropriate in context), check to see if the requested semaphore...
108
6462
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
4
1452
by: David Helgason | last post by:
What: I'm having trouble finding out how to find the current PGconn connection inside a C function. Looking through the documentation didn't give this up. Could anyone suggest where to look? I didn't even see anything similar to this in the SPI_* documentation. Perhaps I am totally mislead here? Why: I am writing an wrapper around librsync, allowing differential updating of large amounts of data (librsync wraps the clever algorithm of
4
11449
by: Greg B | last post by:
Well since getopt() doesn't seem to be compatible with Windows, and the free implementation of it for Windows that I found still had some annoying restrictions, I thought I'd whip up a simple parser myself. Just wanted to see if anyone could provide me with some constructive criticism :) any feedback would be greatly appreciated ----------------------------------------------------------------------------- #include "stdio.h" #include...
5
2146
by: tshad | last post by:
I am trying to access my log files and am running into a permissions problem. I am doing the following: ****************************************************************** private void PopulateSiteBox() { drpSiteBox.Items.Clear(); string FILE_PATH = @"\\" +txtMachine.Text +
35
5513
by: Alex Martelli | last post by:
Having fixed a memory leak (not the leak of a Python reference, some other stuff I wasn't properly freeing in certain cases) in a C-coded extension I maintain, I need a way to test that the leak is indeed fixed. Being in a hurry, I originally used a q&d hack...: if sys.platform in ('linux2', 'darwin'): def _memsize(): """ this function tries to return a measurement of how much memory this process is consuming, in some arbitrary unit...
5
3647
by: snicks | last post by:
I'm trying to exec a program external to my ASP.NET app using the following code. The external app is a VB.NET application. Dim sPPTOut As String sPPTOut = MDEPDirStr + sID + ".ppt" Dim p As New System.Diagnostics.Process 'p.Start(MDEPDirStr & "macrun.exe", sPPTOut) p.Start("C:\WINDOWS\SYSTEM32\CALC.EXE") 'p.Start("C:\WINDOWS\SYSTEM32\macrun.exe", sPPTOut)
4
4102
by: NancyJ | last post by:
Currently we have a database with a main table containing 3 million records - we want to increase that to 10 million but thats not a possibility at the moment. Nearly all 3 million records are deleted and replaced every day - all through the day - currently we're handling this by having 2 sets of tables - 1 for inserting, 1 for searching. A block of records (10k - 1 million) (distinguished by a client identifier field) happen on the...
58
4934
by: sh.vipin | last post by:
is there any way to find out number of bytes freed on a particular free() call in C
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9489
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10357
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10101
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5528
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2893
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.