C++ 为什么线程花费的时间比进程花费的总时间多?

C++ 为什么线程花费的时间比进程花费的总时间多?,c++,multithreading,c++11,time,eigen,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

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

我创建了四个线程,并像这样调用了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;
}
执行后,整个执行所花费的时间显示不正确。操作所用的时间约为22秒,但代码给出的时间约为32秒。我已经从秒表检查过了,该代码的输出不正确

根据

为了测量在程序中花费的时间,应该调用clock()
在程序开始时,从值中减去其返回值
由后续调用返回。clock()返回的值是为
具有不同分辨率时钟的系统之间的兼容性。
要确定以秒为单位的时间,clock()返回的值应为
除以每秒宏时钟的值。定义了每秒时钟数
一百万美元。
但是,此时间计算代码返回的时间与IDE提供的时间相矛盾。我在这里使用的是code::blocks


我遗漏了什么吗?

因为您使用的是C++11,所以可以使用:

std::chrono::time\u点开始、结束;
开始=标准::时钟::系统时钟::现在();
//这里的计算。。。
end=std::chrono::system_clock::now();
std::chrono::持续时间=结束-开始;

std::cout
clock()
不测量时间,只测量CPU周期?@MarcellFülöp所以问题在于clock()。让我检查一下文档,我很快就会把贝克给你。@MarcellFülöp你能看一下这个吗?时钟()返回实际使用的CPU时间。相关:@DieterLücking一个线程使用的实际CPU时间怎么可能超过一个进程占用的总时间…?我在
行中得到一个错误,最后一行有问题,我用这个替换它<代码>cout
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks)/CLOCKS_PER_SEC;
return diffms;
}
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>.
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";