簡體   English   中英

Eratosthenes算法篩分N次運行期間執行時間高峰的原因

[英]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查看它們何時發生。
  • 未預熱時,代碼運行速度會變慢。 循環或方法需要調用10000次才能觸發后台編譯。 您可以使用
    -XX:CompileThreshold=10000
  • 由於調度程序的工作方式,您的計算機將具有明顯的抖動。 除非您將線程綁定到隔離的CPU,否則僅由於這個原因,您就可以預期2-10 ms的抖動。 http://vanillajava.blogspot.com/2013/07/micro-jitter-busy-waiting-and-binding.html

我會更改您的循環以避免使用*在現代CPU上速度很快,但不如+

for (int j = i, m = i * i; m <= N; j++, m += i) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM