小编gok*_*oku的帖子

python 中平方所需的时间

我想知道 x**2 还是 x*x 更快

def sqr(x):
    for i in range (20):
        x = x**2
    return x
def sqr_(x):
    for i in range (20):
        x = x*x
    return x
Run Code Online (Sandbox Code Playgroud)

当我计时时,这就是我得到的:

The time it takes for x**2: 101230500
The time it takes for x*x: 201469200
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多很多次,它们要么相等,要么 x ** 2 比 x * x 快。但 x*x 永远不会比 x**2 快。

所以我反驳了代码:

对于 x**2:

  5          12 LOAD_FAST                0 (x)
             14 LOAD_CONST               2 (2)
             16 BINARY_POWER
             18 STORE_FAST               0 (x)
             20 JUMP_ABSOLUTE            8
Run Code Online (Sandbox Code Playgroud)

对于 x*x: …

python performance time assembly integer-arithmetic

5
推荐指数
1
解决办法
1662
查看次数

标签 统计

assembly ×1

integer-arithmetic ×1

performance ×1

python ×1

time ×1