以相同的算法求解1-2000000之間素數的個數,為什麼Java的計算速度要快於C++?
(Java SE 8 )40 milliseconds左右與C++(TDM-GCC 4.9.2 Release)180milliseconds左右
附代碼
C++
#include <iostream>
#include <bitset>
#include <ctime>
using namespace std;
int main()
{
const int N = 2000000;
clock_t cstart = clock();
bitset<N + 1> b;
int count = 0;
int i;
for(i = 2; i <= N; i++)
b.set(i);
i = 2;
while(i * i <= N)
{
if(b.test(i))
{
count++;
int k = 2 * i;
while(k <= N)
{
b.reset(k);
k += i;
}
}
i++;
}
while(i <= N)
{
if(b.test(i))
count++;
i++;
}
clock_t cend = clock();
double millis = 1000.0 * (cend - cstart) / CLOCKS_PER_SEC;
cout << count << "primes\n"
<< millis << "milliseconds\n";
return 0;
}
Java
import java.util.*;
public class Sieve
{
public static void main(String[] args)
{
int n = 2000000;
long start = System.currentTimeMillis();
BitSet b = new BitSet(n + 1);
int count = 0;
int i;
for(i = 2; i <= n; i++)
b.set(i);
i = 2;
while(i * i <= n)
{
if(b.get(i))
{
count++;
int k = 2 * i;
while(k <= n)//將所有i的倍數位置為關閉狀態
{
b.clear(k);
k += i;
}
}
i++;
}
while(i <= n)
{
if(b.get(i)) count++;
i++;
}
long end = System.currentTimeMillis();
System.out.println(count + " primes");
System.out.println((end - start) + " milliseconds");
}
}
從結果看,肯定是同等硬件條件下,JDK8對代碼的優化比TDM-GCC 4.9.2要好了,使用了更優的CPU指令。