【发布时间】:2012-01-05 07:08:18
【问题描述】:
我有以下代码:
<?php
$start = 1;
$timestart = microtime(1);
for ($i = 0; $i < 1000000; $i++) {
$result1 = $start * 4;
}
echo "\n";
echo microtime(1) - $timestart;
echo "\n";
$timestart = microtime(1);
for ($i = 0; $i < 1000000; $i++) {
$result2 = $start << 2;
}
echo "\n";
echo microtime(1) - $timestart;
echo "\n";
这个输出:
0.14027094841003
0.12061500549316
我在网上找到了一个谷歌面试问题(我想申请一个开发人员,但我意识到我做不到),其中一个问题问最快的方法是乘以一个数字。我的第一个想法是使用* 符号,所以我测试了它。
我的问题是,为什么移位比乘法快?
【问题讨论】:
-
因为乘法需要...乘法...比位移需要更多时间,因为它是一个更复杂的操作?
-
@Dan - 这个问题可能更多地与为什么位移可能或可能不等同于 PHP 中的整数/浮点乘法有关。
-
参见 en.wikipedia.org/wiki/Multiplication_algorithm#Electronic_usage 声明
To multiply two numbers with n digits using this method, one needs about n2 operations. More formally: using a natural size metric of number of digits, the time complexity of multiplying two n-digit numbers using long multiplication is Θ(n2).位移是一条指令。 -
顺带一提,还有more ways to perform multiplication than one might expect——不同的情况下有不同的方法擅长。
-
@drew010; linear-time algorithm is available——假设你有一些表的内存。
标签: php bit-shift multiplication