aablinov / psutil.cr

Psutils.cr is a Crystal port of https://github.com/shirou/gopsutil
19 stars 3 forks source link

CPU usage percentage #3

Open bararchy opened 6 years ago

bararchy commented 6 years ago

Would you say this should give me the best overall % of CPU usage?

(Psutil.cpu_times.first.user + Psutil.cpu_times.first.system) / 1000
bararchy commented 6 years ago

So, following this guide: https://github.com/Leo-G/DevopsWiki/wiki/How-Linux-CPU-Usage-Time-and-Percentage-is-calculated#formula

The right way to calculate is this:

total_time_used = Psutil.cpu_times.first.user + Psutil.cpu_times.first.system + Psutil.cpu_times.first.nice + Psutil.cpu_times.first.nice + Psutil.cpu_times.first.softirq + Psutil.cpu_times.first.irq + Psutil.cpu_times.first.steal + Psutil.cpu_times.first.idle + Psutil.cpu_times.first.iowait
total_time_idle = Psutil.cpu_times.first.iowait + Psutil.cpu_times.first.idle
time_used = total_time_used - total_time_idle
time_used / total_time_used * 100 # this is the % of cpu used
bararchy commented 6 years ago

@kodnaplakal Maybe it can be nice to add a small method for this?

aablinov commented 6 years ago

@bararchy For calculate CPU usage you need interval, take Psutil.cpu_times sleep N take Psutil.cpu_times again and see difference. For example please see in gopsutil https://github.com/shirou/gopsutil/blob/master/cpu/cpu.go#L139

aablinov commented 6 years ago

@bararchy if you can do it yourself, please create a PR if not I will do it today.