问题描述
我正在运行 .cpp 代码 (i) 以顺序样式和 (ii) 使用 OpenMP 语句.我正在尝试查看时差.为了计算时间,我用这个:
I am running a .cpp code (i) in sequential style and (ii) using OpenMP statements. I am trying to see the time difference. For calculating time, I use this:
#include <time.h>
.....
main()
{
clock_t start, finish;
start = clock();
.
.
.
finish = clock();
processing time = (double(finish-start)/CLOCKS_PER_SEC);
}
时间在代码的顺序(上面)运行中非常准确.运行这个大约需要 8 秒.当我在代码中插入 OpenMP 语句然后计算时间时,我得到的时间减少了,但是在控制台上显示的时间大约是 8-9 秒,而实际上它的实时时间只有 3-4 秒!
The time is pretty accurate in sequential (above) run of the code. It takes about 8 seconds to run this. When I insert OpenMP statements in the code and thereafter calculate the time I get a reduction in time, but the time displayed is about 8-9 seconds on the console, when actually its just 3-4 seconds in real time!
这是我的代码的抽象外观:
Here is how my code looks abstractly:
#include <time.h>
.....
main()
{
clock_t start, finish;
start = clock();
.
.
#pragma omp parallel for
for( ... )
for( ... )
for (...)
{
...;
}
.
.
finish = clock();
processing time = (double(finish-start)/CLOCKS_PER_SEC);
}
当我运行上面的代码时,我得到了时间的减少,但显示的时间在实时方面并不准确.在我看来,clock() 函数似乎正在计算每个线程的单独时间并将它们相加并显示出来.
When I run the above code, I get the reduction in time but the time displayed is not accurate in terms of real time. It seems to me as though the clock () function is calculating each thread's individual time and adding up them up and displaying them.
有人可以告诉我这样做的原因或建议我使用任何其他计时函数来测量 OpenMP 程序中的时间吗?
Can someone tell the reason for this or suggest me any other timing function to use to measure the time in OpenMP programs?
谢谢.
推荐答案
我见过 clock() 报告 CPU 时间,而不是实时.
I've seen clock() reporting CPU time, instead of real time.
你可以使用
struct timeval start, end;
gettimeofday(&start, NULL);
// benchmark code
gettimeofday(&end, NULL);
delta = ((end.tv_sec - start.tv_sec) * 1000000u +
end.tv_usec - start.tv_usec) / 1.e6;
改为计时
这篇关于在 C++ OpenMP 代码中测量执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!