【发布时间】:2014-07-13 12:32:36
【问题描述】:
我正在执行代码来计算矩阵乘法代码所花费的时间。
我创建了四个线程并像这样调用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 秒。我从秒表检查过,这段代码的输出不正确。
根据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。
我错过了什么吗?
【问题讨论】:
-
clock()不测量时间,只测量 CPU 周期? -
@MarcellFülöp 所以问题出在时钟()中。让我检查文档,我会尽快回复您。
-
@MarcellFülöp 请你看看这个pubs.opengroup.org/onlinepubs/7908799/xsh/clock.html
-
clock() 返回实际使用的CPU时间。相关:stackoverflow.com/questions/2134363/…
-
@DieterLücking 一个线程使用的实际 CPU 时间怎么会超过一个进程所用的总时间......??
标签: c++ multithreading c++11 time eigen