本文共 729 字,大约阅读时间需要 2 分钟。
#include#include using namespace std;template void measure(T&& func){ using namespace std::chrono; auto start = system_clock::now(); func(); duration diff = system_clock::now() - start; cout << "elapsed: " << diff.count() << "seconds" << endl;}// [a,b)void sum(long start, long end, long &ans){ long s = 0; for (long i = start; i < end; i++) { s = s + i; } ans = s;}const long s = 100000000;int main(){ measure([]() { long ans1, ans2; thread t1 = thread(sum, 0, s / 2, std::ref(ans1)); thread t2 = thread(sum, s / 2, s, std::ref(ans2)); t1.join(); t2.join(); cout << (ans1 + ans2) << endl; }); measure([]() { long ans; sum(0, s, ans); cout << ans << endl; }); system("pause");}
转载地址:http://mqhv.baihongyu.com/