为什么线程花费的时间超过进程占用的总时间?

时间:2014-07-13 12:32:37

标签: c++ multithreading c++11 time eigen

我正在执行代码来计算矩阵乘法代码所用的时间。

我创建了四个线程,并像这样调用Calculate方法:

std::thread t1( Calculate );
std::thread t2( Calculate );
std::thread t3( Calculate );
std::thread t4( Calculate );
t1.join();
t2.join();
t3.join();
t4.join();

这是我正在进行矩阵乘法的代码

void calculate()
{
clock_t starttime = clock();
//  some Code
clock_t endtime = clock();
cout << "Time Taken:"<<diffclock(endtime, starttime)<<"sec."<<endl;
}

这是计算时差的方法:

double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks)/CLOCKS_PER_SEC;
return diffms;
}

执行后,整个执行所用的时间显示不正确。操作所花费的时间约为22秒,但代码占用的时间约为32秒。我已经从秒表检查了它,并且此代码的​​输出不正确。

This is the screen-shot of console output

根据clock

的文档
In order to measure the time spent in a program, clock() should be called
at the start of the program and its return value subtracted from the value 
returned by subsequent calls. The value returned by clock() is defined for
compatibility across systems that have clocks with different resolutions.
To determine the time in seconds, the value returned by clock() should be 
divided by the value of the macro CLOCKS_PER_SEC. CLOCKS_PER_SEC is defined 
to be one million in <time.h>.

但是,此时计算代码返回的时间与IDE提供的时间相矛盾。我在这里使用code :: blocks。

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

由于您使用的是C ++ 11,因此可以使用std::chrono

std::chrono::time_point<std::chrono :: system_clock> start, end;
start = std::chrono::system_clock::now();
// calculations here...
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed = end-start;
std::cout << "Elapsed time: " << elapsed.count() << "s\n";

请注意,访问cout时也应使用std::mutex。你的代码看起来很好,但cout可能会混淆不清。