分析python程序運行時間的幾種方法


最早見過手寫的,類似於下面這種:

  1 import datetime
  2 
  3 def time_1():
  4     begin = datetime.datetime.now()
  5     sum = 0
  6     for i in xrange(10000000):
  7         sum = sum + i
  8     end = datetime.datetime.now()
  9     return end-begin
 10 
 11 print time_1()

輸出如下:

➜  Python python time_1.py
0:00:00.280797

 

另外一種方法是使用timeit模塊,使用方法如下:

In [5]: import timeit

In [6]: timeit.timeit("sum(range(100))")
Out[6]: 1.2272648811340332

還可以在命令行上使用這種timeit模塊,如下:

➜  Python python -m timeit -s"import time_1 as t" "t.time_1()"
0:00:00.282044

10 loops, best of 3: 279 msec per loop

注意:timeit模塊會多次運行程序以獲得更精確的時間,所以需要避免重復執行帶來的影響。比方說x.sort()這種操作,因為第一次執行之后,后邊已經是排好的了,准確性就收到了影響。

 

還有一種方法是使用cProfile模塊,代碼如下,名字為time_1.py:

  1 import datetime
  2 
  3 def time_1():
  4     begin = datetime.datetime.now()
  5     sum = 0
  6     for i in xrange(10000000):
  7         sum = sum + i
  8     end = datetime.datetime.now()
  9     return end-begin
 10 
 11 if __name__ == '__main__':
 12     print time_1()
 13 
 14 import cProfile
 15 cProfile.run('time_1()')

運行程序結果如下:  

➜  Python python time_1.py
0:00:00.282828
         2 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


Traceback (most recent call last):
  File "time_1.py", line 15, in <module>
    cProfile.run('main()')
  File "/usr/lib/python2.7/cProfile.py", line 29, in run
    prof = prof.run(statement)
  File "/usr/lib/python2.7/cProfile.py", line 135, in run
    return self.runctx(cmd, dict, dict)
  File "/usr/lib/python2.7/cProfile.py", line 140, in runctx
    exec cmd in globals, locals
  File "<string>", line 1, in <module>
NameError: name 'main' is not defined
➜  Python vi time_1.py 
➜  Python python time_1.py
0:00:00.284642
         5 function calls in 0.281 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.281    0.281 <string>:1(<module>)
        1    0.281    0.281    0.281    0.281 time_1.py:3(time_1)
        2    0.000    0.000    0.000    0.000 {built-in method now}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

一開始代碼里最后一行寫的是cProfile.run('main()'),提示沒有main(),將main()改成函數名字就可以了

 

這里是最簡單的應用,具體大家可以去看看文檔,或者直接help(xxx)  

 

 

好物、羊毛線報群,需要的可加QQ群 1049623906

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM