我用C++编写了一个非常简单的多线程示例。为什么多线程和单线程具有近似相同的执行时间?
代码:
#include <iostream>
#include <thread>
#include <ctime>
using namespace std;
// function adds up all number up to given number
void task(int number)
{
int s = 0;
for(int i=0; i<number; i++){
s = s + i;
}
}
int main()
{
int n = 100000000;
////////////////////////////
// single processing //
////////////////////////////
clock_t begin = clock();
task(n);
task(n);
task(n);
task(n);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "time single-threading: "<< elapsed_secs << " sec" << endl;
////////////////////////////
// multiprocessing //
////////////////////////////
begin = clock();
thread t1 = thread(task, n);
thread t2 = thread(task, n);
thread t3 = thread(task, n);
thread t4 = thread(task, n);
t1.join();
t2.join();
t3.join();
t4.join();
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "time multi-threading: " << elapsed_secs << " sec" << endl;
}
对我来说,程序的输出是
time single-threading: 0.755919 sec
time multi-threading: 0.746857 sec
我将代码编译为
g++ cpp_tasksize.cpp -std=c++0x -pthread
我在一台24核linux机器上运行。
发布于 2017-06-11 11:16:16
clock()
测量处理器时间,即进程在cpu上花费的时间。在多线程程序中,它会将每个线程花费在cpu上的时间加起来。据报告,单线程和多线程实现的运行时间大致相同,因为它们的总体计算数量是相同的。
你需要的是测量挂钟时间。当您要测量挂钟时间时,请使用chrono
库。
#include <chrono>
int main ()
{
auto start = std::chrono::high_resolution_clock::now();
// code section
auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration<double, std::milli>(end - start).count() << " ms\n";
}
https://stackoverflow.com/questions/44483115
复制相似问题