这是一段看似非常特殊的C++代码.出于某种奇怪的原因,奇迹般地对数据进行排序使得代码几乎快了六倍.
#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) …
Run Code Online (Sandbox Code Playgroud) 该结果我的基准测试表明,性能最差的时候该分支下有15%(或85%)%的概率,而不是50%.
任何解释?
代码太长但相关部分在这里:
private int diff(char c) {
return TABLE[(145538857 * c) >>> 27] - c;
}
@Benchmark int timeBranching(int reps) {
int result = 0;
while (reps-->0) {
for (final char c : queries) {
if (diff(c) == 0) {
++result;
}
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
它计算给定字符串中BREAKING_WHITESPACE字符的数量.结果显示当分支概率达到约0.20时突然下降(性能增加).
关于跌落的更多细节.改变种子表明发生了更多奇怪的事情.请注意,表示最小值和最大值的黑线非常短,除非靠近悬崖.