Oo缘来是你oO

Ruby
require 'benchmark'
def sievePerformance(n)
r = Benchmark.realtime() do
sieve = Array.new(n,true)
sieve[0..1] = [false,false]

2.upto(Integer(Math.sqrt(n)) do |i|
if sieve[i]
(2*i).step(n,i) do |j|
sieve[j] = false
end
end
end
end
r
end

Java
public class GeneratePrimes {
public static double generate(int max) {
long start = System.currentTimeMillis();
boolean sieve[] = new boolean[max];
Arrays.fill(sieve, true);
sieve[0] = false;
sieve[1] = false;
for (int i = 2; i < Math.sqrt(max); i++) {
if (sieve[i]) {
for (int j = 2*i; j < sieve.length; j+=i) {
sieve[j]= false;
}
}
}

return (System.currentTimeMillis() - start)/1000.0;
}

C++
#include <iostream>>
#include <math.h>
#include <sys/time.h>

using namespace std;

double generate(int max) {
struct timeval start;
struct timezone tz;
gettimeofday(&start, &tz);

bool *sieve = new bool[max];
for (int i=0; i<max; i++) sieve[i] = true;
sieve[0] = false;
sieve[1] = false;
for (int n=2; n<sqrt(max); n++) {
if (sieve[n]) {
for (int j=2*n; j<max; j+=n)
sieve[j] = false;
}
}

struct timeval end;
gettimeofday(&end, &tz);

double startSecond = start.tv_usec/1000000.0;
double endSecond = (end.tv_sec - start.tv_sec) + end.tv_usec/1000000.0;
return endSecond - startSecond;
}

int main(int ac, char** av) {
for (int i=100000; i<=5000000; i+=100000) {
double time = generate(i);
cout << time << endl;
}
}

（原文链接网址：http://www.butunclebob.com/ArticleS.UncleBob.SpeedOfJavaCppRuby; Robert C. Martin的英文blog网址：