繁体   English   中英

python timeit:带装饰器的函数

[英]python timeit: function with decorator

我试图弄清楚是否预先编译正则表达式,或者为了启动速度而替代,只在第一次需要它们时编译一次。

我可以使用 timeit 来测试:

re.compile(r'#(?:(?:[\da-f]{3}){1,2}|(?:[\da-f]{4}){1,2})|rgb\(\d{1,3},\d{1,3},\d{1,3}\)')

我不知道如何弄清楚解析器需要多长时间(或如何使用 timeit 来计时)才能看到以下代码(不执行它,只是“看到”它)。

from functools import cache

@cache
def get_color_pattern():
    return re.compile(r'#(?:(?:[\da-f]{3}){1,2}|(?:[\da-f]{4}){1,2})|rgb\(\d{1,3},\d{1,3},\d{1,3}\)')

Python 代码被解释为“从上到下”。 因此,如果您在函数的任一侧声明使用“时间戳”初始化的变量,您可以推断出这些值之间的差异将是解析它们之间的代码所花费的时间。 所以,例如,

from functools import cache
import time
import re

start = time.perf_counter()
@cache
def get_color_pattern():
    return re.compile(r'#(?:(?:[\da-f]{3}){1,2}|(?:[\da-f]{4}){1,2})|rgb\(\d{1,3},\d{1,3},\d{1,3}\)')
print(time.perf_counter()-start)

start = time.perf_counter()
re.compile(r'#(?:(?:[\da-f]{3}){1,2}|(?:[\da-f]{4}){1,2})|rgb\(\d{1,3},\d{1,3},\d{1,3}\)')
print(time.perf_counter()-start)

输出:

5.995000265102135e-06
0.00024428899996564724

因此,我们看到了解析函数与编译表达式所花费的时间差异

如果要检查生成缓存需要多长时间,只需在计时之前运行该函数一次即可生成缓存。

from functools import cache
import re
import timeit

@cache
def get_color_pattern():
    return re.compile(r'#(?:(?:[\da-f]{3}){1,2}|(?:[\da-f]{4}){1,2})|rgb\(\d{1,3},\d{1,3},\d{1,3}\)')

# Run once to generate cache
get_color_pattern()
number = 1000

t = timeit.timeit(get_color_pattern, number=number)

print(f"Total {t} seconds for {number} iterations, {t / number} at average")

输出: Total 4.5900000000001495e-05 seconds for 1000 iterations, 4.5900000000001496e-08 at average

cache注释掉的情况下运行,似乎慢了大约 10 倍: Total 0.0004936999999999997 seconds for 1000 iterations, 4.936999999999997e-07 at average

正如 Kelly Bundy 所指出的, re.compile已经包含一个内置的缓存功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM