我试图证明乘法比除法快多少,但它总是显示相似的时间,我做错了吗?
import warnings
import time
warnings.filterwarnings("ignore", category=DeprecationWarning)
start_time = time.clock()
for i in range(1, 1000000):
x = i + i * 0.33;
print("--- %s seconds ---" % (time.clock() - start_time))
start_time = time.clock()
for i in range(1, 1000000):
x = i + i / 3;
print("--- %s seconds ---" % (time.clock() - start_time))
输出为:
--- 0.62449341 seconds ---
--- 0.6291437290000002 seconds ---
这是我的第一篇文章,因此我无法投票,非常感谢您的回答!
答案 0 :(得分:1)
在您的情况下,乘法速度提高了0.004650319秒(4.65毫秒)。差异不是很明显的原因是因为for循环需要时间。
使用时间:
python -m timeit "0.001 * 100"
>>> 100000000 loops, best of 3: 0.0111 usec per loop
python -m timeit "100 / 1000"
>>> 10000000 loops, best of 3: 0.0328 usec per loop
python -m timeit "for i in range(10000000): pass"
>>> 10 loops, best of 3: 338 msec per loop
由此可知,乘法运算大约比除法运算快3倍。另外,for循环本身比乘法或除法运算花费更多的时间。
要解决此问题,您应将计时置于for循环内:
total_time = 0
for i in range(1, 1000000):
start_time = time.clock()
x = i + i * 0.33;
total_time += time.clock() - start_time
print("--- %s seconds ---" % total_time)
答案 1 :(得分:1)
编辑: 如您所见,乘法不一定是这里更快的运算。取决于编译器如何优化事物。
-
最有可能的是,其余的计算加起来就是时间。
仅尝试乘法/除法时
In [2]: %timeit [i * 0.33 for i in range(1_000_000)]
123 ms ± 1.54 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [3]: %timeit [i * 1/3 for i in range(1_000_000)]
150 ms ± 9.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [4]: %timeit [i /3 for i in range(1_000_000)]
102 ms ± 1.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
尝试不进行总和/赋值运算
In [5]: %timeit x = 5
16.9 ns ± 0.0717 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
In [6]: %timeit 5
10.8 ns ± 0.0264 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
In [7]: %timeit x = 10 / 2
16.9 ns ± 0.0986 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
In [8]: %timeit 10 / 2
10.7 ns ± 0.0103 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)