[英]Reasons of the execution time spikes during N runs of Sieve of Eratosthenes algorithm
我用Java開發了Eratosthenes算法的Sieve,我想衡量它的性能。
基本上,我運行“核心算法”(不是整個應用程序)5000次(使用for循環)並測量其執行時間。
這是我使用的代碼:
int N = 100000;
int m;
long[] microseconds = new long[5000];
for (int k = 0; k < 5000; k++) {
long start = System.nanoTime();
// Core algorithm
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
for (int i = 2; i * i <= N; i++) {
if (isPrime[i]) {
for (int j = i; (m = i * j) <= N; j++) {
isPrime[m] = false;
}
}
}
long end = System.nanoTime();
microseconds[k] = (end - start) / 1000;
}
// Output of the execution times on file
PrintWriter writer = null;
try {
writer = new PrintWriter("ex.txt");
} catch (FileNotFoundException ex) {
Logger.getLogger(EratosthenesSieve.class.getName()).log(Level.SEVERE, null, ex);
}
// iterate through array, write each element of array to file
for (int i = 0; i < microseconds.length; i++) {
// write array element to file
writer.print(microseconds[i]);
// write separator between array elements to file
writer.print("\n");
}
// done writing, close writer
writer.close();
結果如下:
如您所見,存在一些較大的初始峰值(7913和1548)和一些“周期性”峰值。 我該如何解釋這些峰值? 我已經禁用了Internet連接(硬件板)以及所有可能在后台運行的服務(Windows 7;這意味着沒有防病毒等)。 此外,我將-Xmx和-Xms參數設置為非常大量的內存。 因此,我基本上是“單獨”運行該應用程序的。
我知道這是一個難題,但是有些提示將不勝感激。
編輯:我已經修改了基於“ beny23”建議的算法,現在不再有周期性的峰值。 但是,最初會有一些大的峰值。
或(N = 1000,不再是N = 10000):
最有可能的
-verbose:gc
查看它們何時發生。 -XX:CompileThreshold=10000
我會更改您的循環以避免使用*
在現代CPU上速度很快,但不如+
for (int j = i, m = i * i; m <= N; j++, m += i) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.