简体   繁体   English

为什么单次加法比单次加法加单次赋值需要更长的时间?

[英]Why single addition takes longer than single additions plus single assignment?

Here is the python code, I use python 3.5.2/Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz :这是 python 代码,我使用 python 3.5.2/Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz:

import time

empty_loop_t = 0.14300823211669922
N = 10000000


def single_addition(n):
    a = 1.0
    b = 0.0
    start_t = time.time()
    for i in range(0, n):
        a + b
    end_t = time.time()
    cost_t = end_t - start_t - empty_loop_t

    print(n,"iterations single additions:", cost_t)
    return cost_t

single_addition(N)


def single_addition_plus_single_assignment(n):
    a = 1.0
    b = 0.0
    c = 0.0
    start_t = time.time()
    for i in range(0, n):
        c = a + b
    end_t = time.time()
    cost_t = end_t - start_t - empty_loop_t

    print(n,"iterations single additions and single assignments:", cost_t)
    return cost_t

single_addition_plus_single_assignment(N)

The output is:输出是:

10000000 iterations single additions: 0.19701123237609863
10000000 iterations single additions and single assignments: 0.1890106201171875

Normally, to get a more reliable result, it is better to do the test using K-fold.通常,为了获得更可靠的结果,最好使用 K-fold 进行测试。 However, since K-fold loop itself has influence on the result, I don't use it in my test.但是,由于 K-fold 循环本身对结果有影响,所以我没有在我的测试中使用它。 And I'm sure this inequality can be reproduced, at least on my machine.而且我确信这种不等式可以重现,至少在我的机器上是这样。 So the question is why this happened?所以问题是为什么会发生这种情况?

I run it with pypy (had to set empty_loop_t = 0) and got the following results:我用pypy运行它(必须设置empty_loop_t = 0)并得到以下结果:

(10000000, 'iterations single additions:', 0.014394044876098633)
(10000000, 'iterations single additions and single assignments:', 0.018398046493530273)

So I guess it's up to what interpreter does with the source code and how interpreter executes it.所以我想这取决于解释器如何处理源代码以及解释器如何执行它。 It might be that deliberate assignment takes less operations and workload than disposing of the result with non-JIT interpreter while JIT-compiler forces the code to perform the actual number of operations.与使用非 JIT 解释器处理结果相比,故意分配可能需要更少的操作和工作量,而 JIT 编译器会强制代码执行实际的操作数量。

Furthermore, the use of JIT-interpreter makes your script run ~50 times faster on my configuration.此外,使用 JIT 解释器可以使您的脚本在我的配置上运行速度提高约 50 倍。 If you general aim is to optimize the running time of your script you are probably to look that way.如果您的总体目标是优化脚本的运行时间,您可能会这样看。

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

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