python – 为什么时间错误报告这么快的时间?
发布时间:2020-12-20 12:06:27 所属栏目:Python 来源:网络整理
导读:参见英文答案 Why does Python “preemptively” hang when trying to calculate a very large number?????????????????????????????????????2个 我正在玩大数字,并编写以下代码: import timedef ispow2(n): return not n n - 1start = time.clock()ispow2(
参见英文答案 >
Why does Python “preemptively” hang when trying to calculate a very large number?????????????????????????????????????2个
我正在玩大数字,并编写以下代码: import time def ispow2(n): return not n & n - 1 start = time.clock() ispow2(2**100000000) end = time.clock() print(end - start) 令人惊讶的是,这输出0.016864107385627148,而且时间非常短.然而,它实际上需要大约8秒,而不是0.02秒. 为什么时间模块报告这么快的时间显然需要比运行代码更长的时间? 根据 注意:这是从IDLE运行的.当我从命令行运行时,时间似乎准确报告.也许pythonw.exe与此有关,但是什么? 但是,当我在2 ** 10 …的末尾添加另一个0时,命令行需要约7秒,但报告为0.1781140373572865. 解决方法
python.exe和pythonw.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) 等待后完全生成以下输出: program entered 0.01701506924359556 所以程序甚至在大部分等待之后都没有运行. 数据暗示这是2 ** …部分(从命令行运行): power of two|approximate wait time|reported time 1000000000 | 6 seconds |0.1637752267742188 10000000000 | 62 seconds |1.6400543291627092 在最后一次运行中,输入的程序输出和1.6400543291627092之间有明显的~1.5秒等待. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |