Python循环速度源

时间:2014-09-01 13:22:37

标签: python performance list if-statement append

假设我输入了1000万行。 我想知道这需要多长时间:

if line not in list:
  list.append(line)

是否有任何其他类型的网站或来源可以告诉我各种任务的大致速度?

2 个答案:

答案 0 :(得分:3)

您可以使用以下方法获取程序的总运行时间:

time python3 program.py

在您的终端中。它的输出类似于:

real    0m0.184s
user    0m0.032s
sys     0m0.015s

您可以通过以下方式获取特定函数运行n次所需的时间:

from timeit import timeit

def foo():
    return 123456789 + 987654321

n = 10000000
time = timeit(foo, number=n)
print(time)

您还可以计算代码部分与time

的合计时间
from time import time

start = time()

# code to be timed

finish = time()
print(finish - start)

答案 1 :(得分:1)

在终端上运行此命令:

time python your_file.py

结果必须是这样的:

real    0m0.018s
user    0m0.009s
sys     0m0.009s

real - refers to the actual elasped time 
user - refers to the amount of cpu time spent outside of kernel
sys - refers to the amount of cpu time spent inside kernel specific functions

在ConcernedOfTunbridgeWells的THIS stachoverflow回复中详细了解realusersys

要查找ech行的性能,您必须使用分析器逐行定时和执行频率,因此line_profiler是一种简单且不显眼的方式来分析您的代码并用于查看速度和方式通常,每行代码都在脚本中运行。您可以安装由Robert Kern编写的line_profiler,您可以通过pip安装python包:

$ pip install line_profiler

阅读文档HERE