<p>用<code>timeit</code>测试它:</p>
<pre><code>$ bin/python -mtimeit -n10000000 -s 'n = 1.345' 'int(n)'
10000000 loops, best of 3: 0.234 usec per loop
$ bin/python -mtimeit -n10000000 -s 'n = 1.345' 'n // 1'
10000000 loops, best of 3: 0.218 usec per loop
</code></pre>
<p>所以楼层划分只是一个很小的差距。注意,这些值是非常接近的,我不得不增加循环重复计数,以消除对我的机器的随机影响。即使有这么高的计数,你也需要重复几次实验,看看这些数字仍然有多大的变化,在大多数情况下什么样的结果更快。在</p>
<p>这是合乎逻辑的,因为<code>int()</code>需要全局查找和函数调用(因此状态被推送和弹出):</p>
^{pr2}$
<p>是<code>LOAD_GLOBAL</code>和{<cd4>}操作码比<code>LOAD_CONST</code>和{<cd6>}操作码慢;<code>LOAD_CONST</code>是一个简单的数组查找,<code>LOAD_GLOBAL</code>需要执行字典查找。在</p>
<p>将<code>int()</code>绑定到一个本地名称可能会产生一个小的差别,使它再次获得边缘(因为它所做的工作比<code>// 1</code>floor division要少):</p>
<pre><code>$ bin/python -mtimeit -n10000000 -s 'n = 1.345' 'int(n)'
10000000 loops, best of 3: 0.233 usec per loop
$ bin/python -mtimeit -n10000000 -s 'n = 1.345; int_=int' 'int_(n)'
10000000 loops, best of 3: 0.195 usec per loop
$ bin/python -mtimeit -n10000000 -s 'n = 1.345' 'n // 1'
10000000 loops, best of 3: 0.225 usec per loop
</code></pre>
<p>同样,你需要用1000万个循环来运行它,以一致地看到差异。在</p>
<p>也就是说,<code>int(n)</code>更显式,除非您在时间关键的循环中这样做,<code>int(n)</code>在可读性方面胜过<code>n // 1</code>。时间上的差异太小了,不足以让我们去弄清楚什么是值得的。在</p>