【问题标题】:Why the time taken by a thread is more than the total time taken by a process?为什么一个线程所用的时间比一个进程所用的总时间多?
【发布时间】: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。

我错过了什么吗?

【问题讨论】:

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


【解决方案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 可能搞混了。

【讨论】:

  • 我在cout &lt;&lt; "Elapsed time: " &lt;&lt; elapsed.count &lt;&lt; "s\n;error: missing terminating character 的行中遇到错误
  • 最后一行有问题我用这个代替了。 cout &lt;&lt; "Elapsed time: " &lt;&lt; elapsed.count()&lt;&lt;endl; 成功了,谢谢。
猜你喜欢
  • 2021-04-05
  • 2017-12-15
  • 2012-05-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
相关资源
最近更新 更多