liumhh 2020-08-25 13:29 采纳率: 0%
浏览 293

为什么多线程比单线程慢?

#include <iostream>
#include <sys/time.h>
#include <thread>
using namespace std;

long *a = new long[3];
const int count = 1000000000;

void cal(volatile long *a, int index, int total) {
    struct timeval start, end;
    gettimeofday(&start, NULL);
    for (int i = 0; i < total; ++i) {
        a[index]++;
    }

    gettimeofday(&end, NULL);
    long dura = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec);
    cout << dura << endl;
}


int main(){
    struct timeval start, end;
    gettimeofday(&start, NULL);

    cal(a, 0, count);
    cal(a, 1, count);

    gettimeofday(&end, NULL);
    long dura = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec);
    cout << dura << endl;
}
#include <iostream>
#include <sys/time.h>
#include <thread>
using namespace std;

long *a = new long[3];
const int count = 1000000000;

void cal(long *a, int index, int total) {
    struct timeval start, end;
    gettimeofday(&start, NULL);
    int x = 0;
    for (int i = 0; i < total; ++i) {
        a[index]++;
    }
    gettimeofday(&end, NULL);
    long dura = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec);
    cout << dura << endl;
}


int main(){
    struct timeval start, end;
    gettimeofday(&start, NULL);
    std::thread t1(std::bind(cal, a, 0, count));
    std::thread t2(std::bind(cal, a, 1, count));
    t1.join();
    t2.join();
    gettimeofday(&end, NULL);
    long dura = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec);
    cout << dura << endl;
}

其中单线程程序花费4040813ms,
而多线程总是要大于等于4040813ms。

多线程确实是在两个核上跑的,所以应该不是线程切换导致的,我的想法是可能是缓存导致的问题。

  • 写回答

2条回答 默认 最新

  • threenewbee 2020-08-25 13:40
    关注
    for (int i = 0; i < total; ++i) {
        a[index]++;
    }
    

    这是内存敏感型操作,所以无论多少线程,都是在做内存带宽的测试罢了。

    评论

报告相同问题?

悬赏问题

  • ¥15 安装python过程失败怎么解决?
  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?