c++多线程和单线程的性能的小测试

#include<iostream>
#include<thread>
#include<future>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<chrono>
#include<ctime>
using namespace std;
double caculate(double v)
{
    if (v <= 0)
        return v;
    this_thread::sleep_for(chrono::milliseconds(10));//让当前线程暂停
    return sqrt((v * v + sqrt((v-5)*(v+2.5))/2.0)/v);
}

template<typename Iter, typename Fun>
double visitRange(thread::id id,Iter iterBegin,Iter iterEnd,Fun func)
{
    auto curId = this_thread::get_id();
    if (id == curId)
    {
        cout << curId << "hell main thread\n";
    }
    else 
    { 
        cout << curId << "hello work thread\n"; 
    }
    double v = 0;
    for (auto iter = iterBegin; iter != iterEnd; ++iter)
    {
        v += func(*iter);
    }
    return v;
}

int main()
{
    auto mainThreadId = this_thread::get_id();
    vector<double> v;
    for (int i = 0; i < 1000; i++)
    {
        v.push_back(rand());
    }
    cout << v.size() << endl;
    double value = 0.0;
    auto nowc = clock();
    for (auto& info : v) {
        value += caculate(info);
    }
    auto finishc = clock();
    cout <<"single thread: "<< value <<"used"<<(finishc-nowc)<< endl;
    nowc = clock();
    auto iter = v.begin() + (v.size() / 2);
    double anotherv = 0.0;
    auto iterEnd = v.end();
    thread s([&anotherv,mainThreadId,iter, iterEnd]() {
        anotherv = visitRange(mainThreadId,iter, iterEnd, caculate);
        }
    );    //默认是一个函数  拉姆达表达式
    auto id = s.get_id();
    auto halfv = visitRange(mainThreadId,v.begin(),iter,caculate);
    s.join();
    finishc = clock();
    cout << "multithread: "<<(halfv + anotherv)<<"used" << (finishc - nowc) << endl;
    return 0;
}

 

可以看出当运算数据大时,多线程的效率更高

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值