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;
}

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