【问题标题】:Python loop speed sourcesPython循环速度来源
【发布时间】:2023-03-03 07:44:23
【问题描述】:

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

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

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

【问题讨论】:

  • 你试过timeit吗?

标签: python performance list if-statement append


【解决方案1】:

您可以通过以下方式获取程序的总运行时间:

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)

【讨论】:

  • 及时解释打印语句
  • @AWE 我把它简化了。
  • 答案就在几秒钟之内?
【解决方案2】:

在终端上运行这个命令:

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

阅读更多关于 real,user,sys 的信息,请参阅 ConcernedOfTunbridgeWells 的 THIS stachoverflow 回答。

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

$ pip install line_profiler

阅读文档HERE

【讨论】:

    猜你喜欢
    • 2015-11-24
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 2017-07-10
    • 2017-10-06
    相关资源
    最近更新 更多