Here is a piece of C++ code that shows some very peculiar behavior. 這是一段C ++代碼,顯示了一些很是特殊的行爲。 For some strange reason, sorting the data miraculously makes the code almost six times faster: 出於某些奇怪的緣由,奇蹟般地對數據進行排序使代碼快了將近六倍: java
#include <algorithm> #include <ctime> #include <iostream> int main() { // Generate data const unsigned arraySize = 32768; int data[arraySize]; for (unsigned c = 0; c < arraySize; ++c) data[c] = std::rand() % 256; // !!! With this, the next loop runs faster. std::sort(data, data + arraySize); // Test clock_t start = clock(); long long sum = 0; for (unsigned i = 0; i < 100000; ++i) { // Primary loop for (unsigned c = 0; c < arraySize; ++c) { if (data[c] >= 128) sum += data[c]; } } double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC; std::cout << elapsedTime << std::endl; std::cout << "sum = " << sum << std::endl; }
std::sort(data, data + arraySize);
沒有std::sort(data, data + arraySize);
, the code runs in 11.54 seconds. ,代碼將在11.54秒內運行。 Initially, I thought this might be just a language or compiler anomaly, so I tried Java: 最初,我認爲這可能只是語言或編譯器異常,因此我嘗試了Java: ios
import java.util.Arrays; import java.util.Random; public class Main { public static void main(String[] args) { // Generate data int arraySize = 32768; int data[] = new int[arraySize]; Random rnd = new Random(0); for (int c = 0; c < arraySize; ++c) data[c] = rnd.nextInt() % 256; // !!! With this, the next loop runs faster Arrays.sort(data); // Test long start = System.nanoTime(); long sum = 0; for (int i = 0; i < 100000; ++i) { // Primary loop for (int c = 0; c < arraySize; ++c) { if (data[c] >= 128) sum += data[c]; } } System.out.println((System.nanoTime() - start) / 1000000000.0); System.out.println("sum = " + sum); } }
With a similar but less extreme result. 具備類似但不太極端的結果。 數組
My first thought was that sorting brings the data into the cache, but then I thought how silly that was because the array was just generated. 我首先想到的是排序將數據帶入緩存,可是後來我想到這樣作是多麼愚蠢,由於剛剛生成了數組。 緩存
The code is summing up some independent terms, so the order should not matter. 該代碼總結了一些獨立的術語,所以順序可有可無。 less