2011-01-20 54 views
3

考慮下面的例子:諒解CPU秒

import hotshot 
import hotshot.stats 
import time 

def test_sleep(): 
    time.sleep(1) 

def main(): 
    prof = hotshot.Profile("lol.prof") 
    prof.runcall(test_sleep) 
    prof.close() 

    stats = hotshot.stats.load("lol.prof") 
    stats.sort_stats("time", "calls") 
    stats.print_stats(20) 

if __name__ == "__main__": 
    main() 

我得到這樣的輸出:

debian:# python lol.py 
     1 function calls in 1.000 CPU seconds 

    Ordered by: internal time, call count 

    ncalls tottime percall cumtime percall filename:lineno(function) 
     1 1.000 1.000 1.000 1.000 lol.py:6(test_sleep) 
     0 0.000    0.000   profile:0(profiler) 

我預計將有0秒CPU時間和1秒掛鐘時間。

我期望在繁忙的循環的情況下,1個CPU第二,不睡眠的情況下。

有人可以解釋爲什麼我會得到這樣的結果嗎?

謝謝!

回答

1

這聽起來像一個自命不凡的錯誤 - 它不是從OS獲得CPU時間,它變得經過時間(也許減去I/O等待時間,這將是在這種情況下,零)。如果你這樣做time python lol.py你會發現你並不是在忙着等待。

+1

是否記錄在某處?我用cProfile得到了同樣的結果。 「時間python.lol」工作正常。 – lstipakov 2011-01-20 20:57:56