使用自定義裝飾器測量時間
def test_time(func):
def inner(*args, **kw):
t1 = datetime.datetime.now()
print('開始時間:', t1)
func(*args, **kw)
t2 = datetime.datetime.now()
print('結束時間:', t2)
print('耗時: ', t2 - t1)
return inner
@test_time
def call():
a = list()
for i in range(1000 * 10000):
a .append(i)
輸出結果:
開始時間: 2019-08-30 22:22:01.881215
結束時間: 2019-08-30 22:22:02.816677
耗時: 0:00:00.935462
使用cProfile
在學習過程中有什麼不懂得可以加
我的python學習交流扣扣qun,688244617
羣裏有不錯的學習教程、開發工具與電子書籍。
與你分享python企業當下人才需求及怎麼從零基礎學習好python,和學習什麼內容。
def func():
a2 = list()
for i in range(100000):
a2.append(i)
if __name__ == '__main__':
al = list()
for i in range(2000000):
al.append(i)
func()
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.254 0.254 0.405 0.405 test.py:8()
1 0.009 0.009 0.013 0.013 test.py:8(func)
1 0.000 0.000 0.405 0.405 {built-in method builtins.exec}
2100000 0.142 0.000 0.142 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
能夠顯示各種操作的耗時。
更直觀的逐行代碼時間測量line_profiler
沒裝成功。