【问题标题】:Timeit module, triple quotes code vs function [closed]Timeit 模块,三引号代码与函数 [关闭]
【发布时间】:2020-07-28 09:29:51
【问题描述】:

我使用timeit 模块来衡量我的代码的一些执行情况,在检查不同的脚本时,我发现“相同的脚本”有很大的不同,但以不同的方式定义。

代码.py 导入时间

code = '''
def count():
    for i in range(100):
        pass
'''
   
def count():
    for i in range(100):
        pass

print(timeit.timeit(code))
print(timeit.timeit(count))

输出:

0.17939981000017724
3.7566073690004487

幕后究竟发生了什么?我的意思是,在这两种情况下,这段代码是完全一样的,但是执行的时间差异很大。

【问题讨论】:

  • 字符串code中的源代码只是定义了一个函数,它实际上并没有运行这个函数。

标签: python performance time timeit


【解决方案1】:

在字符串示例中,您只是在定义函数而不是实际调用它,因此您实际上是在计时函数的创建而不是执行它。

您需要在 code 字符串的末尾附加一个 count() 函数调用,以便它实际运行并包含在分析中。

code = '''
def count():
    for i in range(100):
        pass
count()
'''

但请注意,从技术上讲,您在字符串示例中同时对函数声明和执行进行计时,而在第二个示例中仅对函数调用进行计时。

这将是一个更公平的比较:

code = '''
def count():
    for i in range(100):
        pass
'''
   
def count2():
    for i in range(100):
        pass

print(timeit.timeit("count()", setup=code))
print(timeit.timeit(count2))

【讨论】:

    【解决方案2】:

    code 只是一个字符串而不是函数定义。

    code = '''
    def count():
        for i in range(100):
            pass
    '''
    

    它不执行任何计算或迭代。 code:

    '\ndef count():\n    for i in range(100):\n        pass\n'
    

    count 是:

    <function __main__.count()>
    

    【讨论】:

    • 但是变量code 只是纯文本,对吗?我的意思是,如果没有 compile() 函数或类似的东西,我不能调用既不执行code 中的代码,可以吗?
    • timeit 执行作为字符串提供的代码。比较timeit.timeit("""print(3)""")。问题恰恰在于code一个函数定义的字符串——而不是它的执行。
    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    相关资源
    最近更新 更多