分析时解密“这可能意味着中间结果正在被缓存”

2024-04-26 00:34:39 发布

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

我得到了两个基本上做相同事情的函数,我想比较它们的运行时性能。你知道吗

def calculate_bonus_by_table(data, value):
    cdf = data["cdf"]

    # CAUTION: the following loop doesn't do bound checking
    i = 0
    while (value > cdf[i]): i += 1

    return data['bonus'][i]

def calculate_bonus_by_regression(data, value):
    max_slope = len(data['bonus']) - 1
    slope = int((value - 1) / 6)
    if slope > max_slope:
        slope = max_slope

    slope += 1
    return (0.205078125 * slope**2) + (0.68359375 * slope) - 70.888671875

data = json.load(open('bonus.json'))    

上面使用的JSON文件的一个片段

{ "cdf": [6, 12, 18, 24, 30, 36, ...], "bonus": [-70, -68, -66, -64, -62, ...] }

在iPython中,我将两个函数分别计时

%timeit calculate_bonus_by_table(data, 199)
1000000 loops, best of 3: 1.64 µs per loop

%timeit calculate_bonus_by_regression(data, 199)
The slowest run took 7.99 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 604 ns per loop

对这两个函数多次运行timeit总是得到类似的结果。..u by \u回归函数的结果总是给出有关缓存的警告。你知道吗

如果一个缓存了,而另一个没有缓存,我如何比较这两个呢?为什么按表缓存而按表缓存?在生产环境中使用时,逐层回归性能和缓存是否有效,或者我是否应该假设最差的性能(从上面看,7.99*604ns=4.83us)?你知道吗

谢谢


Tags: the函数loopdatabyvaluedeftable