I am able to get current cpu usage details using following code
import psutil as PSUTIL
PSUTIL.cpu_percent(interval=1)
My question is; how can i get the past 10 minutes cpu usage details?
I am able to get current cpu usage details using following code
import psutil as PSUTIL
PSUTIL.cpu_percent(interval=1)
My question is; how can i get the past 10 minutes cpu usage details?
The idea is to:
threading
module, or system service/daemon. Something that works parallel to your main code;CPU
load stats, pass it from the background task by IPC
, files
, etc.The exact solution depends on what tools can you use.
Run the python script in background using cronjob
1)Open terminal and type crontab -e
2)Edit the file and write the following code to run the python script in background
*/1 * * * * python /yourpath/yourpythonfile.py
3) Create yourpythonfile.py and write the following code
import psutil as PSUTIL
with open('/yourpath/yourfile.txt', "a") as myfile:
myfile.write(str(PSUTIL.cpu_percent(interval=1))+"%"'\n')
To measure CPU usage, you need to compare the usage at two given time; you can't get measure point from the past (except if you store it, as @ajsp suggested).
For example:
import psutil
import time
def calculate(t1, t2):
# from psutil.cpu_percent()
# see: https://github.com/giampaolo/psutil/blob/master/psutil/__init__.py
t1_all = sum(t1)
t1_busy = t1_all - t1.idle
t2_all = sum(t2)
t2_busy = t2_all - t2.idle
if t2_busy <= t1_busy:
return 0.0
busy_delta = t2_busy - t1_busy
all_delta = t2_all - t1_all
busy_perc = (busy_delta / all_delta) * 100
return round(busy_perc, 1)
cpu_time_a = (time.time(), psutil.cpu_times())
# your code taking time
cpu_time_b = (time.time(), psutil.cpu_times())
print 'CPU used in %d seconds: %s' % (
cpu_time_b[0] - cpu_time_a[0],
calculate(cpu_time_a[1], cpu_time_b[1])
)
Or you could use cpu_percent(interval=600)
; and if you don't want it to block other code in your script you might want to do it in a separate thread.
But as previously said, in both cases this won't go back in time; just measure CPU time from now to interval
.
If you just need to keep track of your CPU usage and don't want to reinvent the wheel, you could use:
Those solutions can help you to save metrics from your system for processing.
You can use os.getloadavg()
to find average load on the server during past 1, 5 & 15 minutes.
May be this turns out to be useful for what you intend to do.