Avatar ·

为什么我的C++代码在数组大小为8192时严重变慢?

大家好。我正在用C++编写一个图像处理程序。发现一个奇怪的问题:当我的数组大小(或循环步长)恰好为8192个元素时,程序运行速度会慢10倍。当大小为8191或8193时,一切飞快。 以下是重现问题的简化代码: ```cpp #include #include #include int main() { const int SIZE = 8192; // 如果改为8191或8193,速度正常 std::vector> matrix(SIZE, std::vector(SIZE, 1)); auto start = std::chrono::high_resolution_clock::now(); long long sum = 0; for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) { sum += matrix[i][j]; } } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration elapsed = end - start; std::cout << "时间: " << elapsed.count() << " 秒, 总和: " << sum << std::endl; return 0; } ```