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