C++ 多线程

文章通过C++代码示例展示了在Ubuntu系统中,使用多线程处理数据相比于单线程的效果。当指定进程使用特定CPU内核时,多线程处理可能会降低性能;而未指定内核时,多线程能提升效率,表明C++多线程默认利用了多核优势。
摘要由CSDN通过智能技术生成

c++使用多线程提速

#include<iostream>
#include <thread>
#include <chrono>
#include <unistd.h> //可以使用sleep函数
using namespace std;
int NUM = 60000;
int TNUM = 2;
int func1(int* ptr){
    for(int i=0; i<NUM; i++){
        *(ptr++) = i;
        // ptr++;
        // cout << *(ptr-1) << endl;
        // ptr++;
    }
    return 0;
}

int func_split_num(int* ptr, int start, int end, int core){
    cpu_set_t mask;
    CPU_ZERO(&mask);
    CPU_SET(core, &mask); // 指定第几个核运行,本程序

    for(int i=start; i<end; i++){
        *(ptr++) = i;
        // sleep(1);
        // cout << *(ptr-1) << endl;
    }
    return 0;
}

int func2(int* ptr){
    thread thread1(func_split_num, ptr, 0, NUM/2, 11); // 线程开始
    thread thread2(func_split_num, ptr+NUM/2, NUM/2, NUM, 13);
    thread1.join(); // 等待线程结束,注意两个join写在最后面
    thread2.join(); 
    return 0;
}

int main()
{
    int* arr = new int [NUM];
    using milli = std::chrono::milliseconds;
    // func1(arr);
    // func2(arr);
    int c =65535;
    auto start = std::chrono::high_resolution_clock::now();
    for(int i=0; i<c; i++){
        func1(arr);
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::cout << "func1: "
    << (float)std::chrono::duration_cast<milli>(end - start).count() 
    << " milliseconds\n";

    start = std::chrono::high_resolution_clock::now();
    for(int i=0; i<c; i++){
        func2(arr);
    }
    end = std::chrono::high_resolution_clock::now();
    std::cout << "func2: "
    << (float)std::chrono::duration_cast<milli>(end - start).count() 
    << " milliseconds\n";

    // 赋值并
    for(int i=0; i<NUM; i++){
        cout << arr[i] << "-check"<< endl;
    }
    return 0;
}

指定进程执行使用cpu内核

taskset -c 11 ./a.out

输出

func1: 10884 milliseconds
func2: 12298 milliseconds

未指定cpu内核

func1: 8933 milliseconds
func2: 6952 milliseconds

结论:ubuntu系统内,进程的内开启两个线程处理数据相比一个线程处理数据,指定进程使用cpu内核,多线程会降低性能,但是未指定运行cpu内核,线程是加速的,由此推理C语言多线程默认使用了多核

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值