C++多线程加速for循环

  • 引用传参需要使用std::ref
  • 普通循环
#include <iostream>
#include <vector>
#include <sys/time.h>
#include <math.h>
using namespace std;

int main(int argc, char **argv) {
  struct timeval start, end;
  vector<vector<double> > a(10000, vector<double>(10000));
  gettimeofday(&start, NULL);
  for(int i = 0; i < 10000; ++i) {
    for(int j = 0; j < 10000; ++j) {
      a[i][j] = cos(1.05);
    }
  }
  gettimeofday(&end, NULL);
  float cost_time = (end.tv_usec-start.tv_usec)/1000000.0 + end.tv_sec-start.tv_sec;
  cout << cost_time << endl;
  cout << a[666][6] << endl;

  return 0;
}
// 输出 0.311707
//     0.497571
  • 多线程
#include <iostream>
#include <vector>
#include <sys/time.h>
#include <math.h>
#include <thread>
using namespace std;

void parallel(vector<vector<double> > &a, int index){
  for(int i = index; i < index+2000; ++i) {
    for(int j = 0; j < 10000; ++j) {
      a[i][j] = cos(1.05);
    }
  }
}

int main(int argc, char **argv) {
  struct timeval start, end;
  vector<vector<double> > a(10000, vector<double>(10000));
  gettimeofday(&start, NULL);
  thread t1(parallel, std::ref(a), 0);
  thread t2(parallel, std::ref(a), 2000);
  thread t3(parallel, std::ref(a), 4000);
  thread t4(parallel, std::ref(a), 6000);
  thread t5(parallel, std::ref(a), 8000);
  t1.join();
  t2.join();
  t3.join();
  t4.join();
  t5.join();
  gettimeofday(&end, NULL);
  float cost_time = (end.tv_usec-start.tv_usec)/1000000.0 + end.tv_sec-start.tv_sec;
  cout << cost_time << endl;
  cout << a[666][6] << endl;

  return 0;
}
// 输出 0.067235
//     0.497571
  • 均分成5个线程,速度提高差不多5倍
  • 3
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刀么克瑟拉莫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值