c++ - 使用一个循环与两个循环
问题描述
我正在阅读这个博客:- https://developerinsider.co/why-is-one-loop-so-much-slower-than-two-loops/。我决定使用 C++ 和 Xcode 进行检查。所以,我写了一个下面给出的简单程序,当我执行它时,我对结果感到惊讶。实际上,与文章中所述相反,与第一个功能相比,第二个功能要慢。谁能帮我弄清楚为什么会这样?
#include <iostream> #include <向量> #include <时间> 使用命名空间 std::chrono; 无效函数1(){ 常量 int n=100000; int a1[n],b1[n],c1[n],d1[n]; for(int j=0;j<n;j++){ a1[j] = 0; b1[j] = 0; c1[j] = 0; d1[j] = 0; } 自动启动 = high_resolution_clock::now(); for(int j=0;j<n;j++){ a1[j] += b1[j]; c1[j] += d1[j]; } 自动停止 = high_resolution_clock::now(); 自动持续时间 = duration_cast<微秒>(停止 - 开始); std::cout << duration.count() << "微秒。" << std::endl; } 无效函数2(){ 常量 int n=100000; int a1[n],b1[n],c1[n],d1[n]; for(int j=0; j<n; j++){ a1[j] = 0; b1[j] = 0; c1[j] = 0; d1[j] = 0; } 自动启动 = high_resolution_clock::now(); for(int j=0; j<n; j++){ a1[j] += b1[j]; } for(int j=0;j<n;j++){ c1[j] += d1[j]; } 自动停止 = high_resolution_clock::now(); 自动持续时间 = duration_cast<微秒>(停止 - 开始); std::cout << duration.count() << "微秒。" << std::endl; } int main(int argc, const char * argv[]) { 函数1(); 函数2(); 返回0; }
解决方案
第二个函数的迭代次数是第一个函数的两倍,这意味着条件分支增加了一倍(在现代 CPU 上仍然相当昂贵),这反过来又导致它变慢。此外,第二个函数必须分配一个额外的迭代器变量,并且它必须将迭代器变量增加两倍的次数。
您的代码与本文中演示的代码之间还有一个主要区别:您的代码在堆栈上分配其数组,而本文的代码在堆上分配其数组。这对阵列如何表现性能具有严重的性能影响。
该文章还提到,对于不同的系统和不同大小的数组,行为可能并不统一。他的文章专门围绕磁盘缓存的含义展开,这些含义可能会或可能不会在您的代码中生效。
推荐阅读
- python - List comprehension in python not evaluating correctly
- oop - 如何解决这个循环依赖问题?
- javascript - 在 TypeScript 中保存代码后是否可以运行 grunt 命令?
- javascript - Checked radio button on select option change
- jsgrid - jsgrid returns blank line after update
- testing - Jmeter - 等待加载网络网格
- c++ - C++ SFML 客户端-服务器游戏 SocketSelector 设计
- scorm - 如何计算 SCORM 内容的进度?
- laravel - laravel vue 将数组发送到后端
- python - 如何从图像中随机裁剪(特定区域和特定概率)矩形