让我们从说明代码可读性胜过微优化开始,我们宁愿把它留给编译器。这只是一个奇怪的案例,其中的细节似乎很有趣,而不是一般性推荐
所以搞乱了一个素数生成器函数,并想出了一个奇怪的行为,其中人们推荐的“!=”是最有效的,实际上是最不有效的,而“<=”是最差的最佳选择。
C#
private static void Main(string[] args) {
long totalTicks = 0;
for (int i = 0; i < 100; ++i) {
var stopWatch = Stopwatch.StartNew();
PrintPrimes(15000);
totalTicks += stopWatch.ElapsedTicks;
}
Console.WriteLine("\n\n\n\nTick Average: {0}", totalTicks / 100);
Console.Read();
}
private static void PrintPrimes(int numberRequired) {
if (numberRequired < 1)
return;
Console.Write("{0}\t", 2);
int primeTest = 3;
/****** UPDATE NEXT TWO LINES TO TEST FOR != *****/
int numPrimes = 2; // set numPrimes = 1 for !=
while (numPrimes <= numberRequired) { // switch <= to !=
if (IsPrime(primeTest)) {
Console.Write("{0}\t", primeTest);
++numPrimes;
}
primeTest += 2;
}
}
private static bool IsPrime(int test) {
for (int i = 3; i * i <= test; i = 2 + i)
if (test % i == 0)
return false;
return true;
}
输出:
<= 1319991
!= 1321251
同样在 C++ 中(在不同的机器上)
include <cstddef>
#include <limits>
int main() {
for(size_t i(0) ; i <= 10000000000 ; ++i);
}
输出:
<=
real 0m16.538s
user 0m16.460s
sys 0m0.000s
~ [master] $ vim d.cc
!=
real 0m16.860s
user 0m16.780s
sys 0m0.000s
循环运行相同的次数。是否有任何<=
不适用的优化!=
或者是一些奇怪的 cpu 行为?