gpt4 book ai didi

python - 计算代码运行 Python 的时间

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:42 25 4
gpt4 key购买 nike

我如何知道 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"

输出:

[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

更新

不要忘记导入时间

将此行 start_time = time.clock() 放在您的代码之前并放置此

在代码末尾打印 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"

你也可以写装饰器来测量时间,

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

关于python - 计算代码运行 Python 的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22963684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com