为什么时间错误报告这么快的时间?

Jus*_*tin 3 python time python-3.x

我正在玩大数字,并编写以下代码:

import time

def ispow2(n):
    return not n & n - 1

start = time.clock()
ispow2(2**100000000)
end = time.clock()

print(end - start)
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,这会输出0.016864107385627148,而且时间非常短.然而,它实际上需要8几秒钟,而不是0.02.

为什么时间模块报告这么快的时间显然需要比运行代码更长的时间?


根据time,clock()已弃用,所以我把它换了process_time().我得到了几乎相同的结果.与...相同perf_counter().


注意:这是从IDLE运行的.当我从命令行运行时,时间似乎准确报告.也许pythonw.exe与此有关,但是什么?

但是,当我添加另一个0结束时2**10...,命令行需要约7秒,但报告0.1781140373572865.

Jus*_*tin 8

python.exepythonw.exe在运行之前优化代码.似乎2**100000000正在预先计算.这个代码的小编辑:

import time

print("program entered")

def ispow2(n):
    return not n & n - 1

start = time.perf_counter()
ispow2(2**100000000)
end = time.perf_counter()

print(end - start)
Run Code Online (Sandbox Code Playgroud)

等待后完全生成以下输出:

program entered
0.01701506924359556
Run Code Online (Sandbox Code Playgroud)

所以程序甚至在大部分等待之后都没有运行.

表明这与2**...部件(从命令行运行)的数据:

power of two|approximate wait time|reported time
1000000000  | 6  seconds          |0.1637752267742188
10000000000 | 62 seconds          |1.6400543291627092
Run Code Online (Sandbox Code Playgroud)

在最后一次运行中,在和1.5的输出之间有一个明显的〜秒等待.program entered1.6400543291627092

  • [`pyCode_Optimize`](http://hg.python.org/cpython/file/04f714765c13/Python/peephole.c#l331)检测字节码模式`LOAD_CONST`,`LOAD_CONST`,`BINOP`,并调用[` fold_binops_on_constants`](http://hg.python.org/cpython/file/04f714765c13/Python/peephole.c#l138)来评估操作并用一个`LOAD_CONST`替换它.如果导入脚本,模块的代码对象将缓存在`__pycache__`目录中,在那里您将看到它是几兆字节,与`sys.getsizeof(2**100000000)`一致. (4认同)