Assuming you want to do this within your program with a builtin, Python's resource
module might be of use to you here. psutil
is a good option (as suggested by Federico) if you're able to install packages.
Outside your program, there are many ways to get CPU usage of an arbitrary process. If you're on *nux and prefer the command line, top
and similar commands should do the job. On a graphical interface, I personally prefer KSysGuard (I'm on Kubuntu). Gnome System Monitor works as well. On Windows, the Task Manager should suffice.
EDIT: psutil
seems to return global usages. If you only wanted the usage of your process you'd be better off with resource
or os.times
, but if you want total CPU utilization (including other processes) psutil
is a more robust solution.
For CPU times in resource
:
import resource
resource.getrusage()[0] # Returns the time in seconds in user mode
# Note that this time accumulates while the program runs,
# so you might want to save its previous value each time you take a measurement