2017-06-19 63 views
0

是否可以檢查簡單腳本的CPU使用情況?python腳本的CPU使用情況

例如:如何獲得100%打印百分比的CPU使用率「hello world!」 ?

目前我得到的執行時間在控制檯,通過:

time -p python script.py 
+0

是嗎?你想要什麼「時間」不讓你? – Tamar

+0

是https://stackoverflow.com/questions/15176619/timing-the-cpu-time-of-a-python-program你在找什麼? – Artyer

+0

你可以看看'top' unix命令。 –

回答

0

你需要的psutil模塊。

import psutil 
print(psutil.cpu_percent()) 
+0

謝謝! :) – user7375796

+1

'psutil.cpu_percent'適用於整個系統,而不是單個進程。對於當前腳本,使用'current_process = psutil.Process();'print(current_process.cpu_percent())'。 – eryksun

1

如果你是在UNIX機器上,你總是可以在一個新的終端開放top然後觀察%使用,同時你運行你的Python程序。或者,您可以使用一些第三方庫。

這裏有一個:Benchmark

實例(從[PY包索引]取(https://pypi.python.org/pypi/Benchmarker/4.0.1)源:

程序:

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 
0

一個你可以做的事情是使用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) 
相關問題