我不明白它是怎么工作的。需要解释一下吗

2024-09-28 05:25:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白我是怎么工作的。我举了一个例子,我想计算处理时间的差异。如果有人有时间帮我把它拆了,我会永远感激的。你知道吗

低音

def main():
    prod_nums = ['V475', 'F987', 'Q143', 'R688']

def search_fast(prod_nums):
    for item in prod_nums:
        if item == 'R688':
            return True
    return False

def search_slow(prod_nums):
    return_value = False
    for item in prod_nums:
        if item == 'R688': 
            return_value = True
    return return_value

Tags: infalsetrueforsearchreturnifvalue
1条回答
网友
1楼 · 发布于 2024-09-28 05:25:07

如果要向函数传递参数,可能需要使用timeit.Timer,但要使列表全局化,如下所示:

prod_nums = ['V475', 'F987', 'Q143', 'R688']

然后运行以下命令:

from timeit import Timer
t = Timer(lambda: search_fast(prod_nums))
print t.timeit() # In my case will print 0.336354970932
t = Timer(lambda: search_slow(prod_nums))
print t.timeit() # 0.374251127243

timeit在您希望检查dev环境中的一小段代码时非常有用。你知道吗

如果函数是这样的:

def search_slow():
    prod_nums = ['V475', 'F987', 'Q143', 'R688']
    return_value = False
    for item in prod_nums:
        if item == 'R688':
            return_value = True
    return return_value

您可以使用timeit.timeit

import timeit
timeit.timeit(search_slow)
>>> 0.3833189010620117

这不会回报你任何结果,只会回报你所花的时间。这是另一个可以使用decorator的场景。 基本上,您可以使用timeit来告诉您执行一个函数需要多少时间,就像终端中的time sample_file.py。你知道吗

基于python文档(https://docs.python.org/2/library/timeit.html): This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.

相关问题 更多 >

    热门问题