【发布时间】:2017-06-19 18:49:07
【问题描述】:
是否可以检查简单脚本的 CPU 使用率?
例如:如何获取打印 100 次“hello world!”的 CPU 使用率百分比?
目前我正在控制台中获取执行时间,通过:
time -p python script.py
【问题讨论】:
-
所以?你想要什么“时间”不让你?
-
可以看
topunix命令。
是否可以检查简单脚本的 CPU 使用率?
例如:如何获取打印 100 次“hello world!”的 CPU 使用率百分比?
目前我正在控制台中获取执行时间,通过:
time -p python script.py
【问题讨论】:
topunix命令。
如果您使用的是 unix 机器,您可以随时在新终端中打开 top,然后在运行 python 程序时观察 % 使用情况。或者,您可以使用一些 3rd 方库。
这是一个:Benchmark
示例(取自py package index)。
程序:
from benchmarker import Benchmarker
## specify number of loop
with Benchmarker(1000*1000, width=20) as bench:
s1, s2, s3, s4, s5 = "Haruhi", "Mikuru", "Yuki", "Itsuki", "Kyon"
@bench(None) ## empty loop
def _(bm):
for i in bm:
pass
@bench("join")
def _(bm):
for i in bm:
sos = ''.join((s1, s2, s3, s4, s5))
@bench("concat")
def _(bm):
for i in bm:
sos = s1 + s2 + s3 + s4 + s5
@bench("format")
def _(bm):
for i in bm:
sos = '%s%s%s%s%s' % (s1, s2, s3, s4, s5)
结果:
$ python example.py -h # show help
$ python example.py -o result.json
## benchmarker: release 4.0.0 (for python)
## python version: 3.4.2
## python compiler: GCC 4.8.2
## python platform: Linux-3.13.0-36-generic-x86_64-with-debian-jessie-sid
## python executable: /opt/vs/python/3.4.2/bin/python
## cpu model: Intel(R) Xeon(R) CPU E5-2670 v2 @ 2.50GHz # 2494.050 MHz
## parameters: loop=1000000, cycle=1, extra=0
## real (total = user + sys)
(Empty) 0.0236 0.0200 0.0200 0.0000
join 0.2779 0.2800 0.2800 0.0000
concat 0.3792 0.3800 0.3800 0.0000
format 0.4233 0.4300 0.4300 0.0000
## Ranking real
join 0.2779 (100.0) ********************
concat 0.3792 ( 73.3) ***************
format 0.4233 ( 65.6) *************
## Matrix real [01] [02] [03]
[01] join 0.2779 100.0 136.5 152.3
[02] concat 0.3792 73.3 100.0 111.6
[03] format 0.4233 65.6 89.6 100.0
【讨论】:
if __name__ == '__main__': 部分?
您需要 psutil 模块。
import psutil
print(psutil.cpu_percent())
【讨论】:
psutil.cpu_percent 适用于整个系统,而不是单个进程。对于当前脚本,请使用 current_process = psutil.Process(); print(current_process.cpu_percent())。
这不会计算 CPU 使用率,而是执行时间。
使用timeit,找出执行的初始时间和程序结束的时间差。例如:
import timeit
start_time = timeit.default_timer()
print("Hello World")
print("Hello World")
print("Hello World")
end_time = timeit.default_timer()
print (end_time - start_time)
【讨论】: