我怎么知道 Python 中代码的执行时间(以微秒为单位)?我试过 time.time 和 timeit.timeit 但我不能有一个好的输出
尝试这个,
import time
def main():
print [i for i in range(0,100)]
start_time = time.clock()
main()
print time.clock() - start_time, "seconds"
Run Code Online (Sandbox Code Playgroud)
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
0.00255163020819 seconds
Run Code Online (Sandbox Code Playgroud)
更新
不要忘记 import time
将此行start_time = time.clock()放在您的代码之前并将其放置
print time.clock() - start_time, "seconds" 在代码的末尾。
更新
# Top Of script file.
def main():
print [i for i in range(0,100)]
start_time = time.clock()
#YOUR CODE HERE - 1
main()
#YOUR CODE HERE - N
print time.clock() - start_time, "seconds"
Run Code Online (Sandbox Code Playgroud)
您还可以编写装饰器来测量时间,
import time
def dec(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print(end - start)
return wrapper
@dec
def test():
for i in range(10):
pass
test()
# output shows here
Run Code Online (Sandbox Code Playgroud)
最简单的方法是这样的,但这要求脚本运行至少十分之一秒:
import time
start_time = time.time()
# Your code here
print time.time() - start_time, "seconds"
Run Code Online (Sandbox Code Playgroud)
还有一些可用的分析器也可以提供帮助。
如果我有一个像这样的小脚本
print "Hello, World!"
Run Code Online (Sandbox Code Playgroud)
并想对其进行分析
>python -m cProfile test.py
Hello, world!
2 function calls in 0.001 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.001 0.001 0.001 0.001 test.py:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
Run Code Online (Sandbox Code Playgroud)
这表明运行时间为 0.001 秒,并且还提供了有关执行代码时发生的调用的其他信息。
| 归档时间: |
|
| 查看次数: |
11642 次 |
| 最近记录: |