gpt4 book ai didi

c - 并行执行时间

转载 作者:行者123 更新时间:2023-11-30 17:05:38 25 4
gpt4 key购买 nike

我很好奇使用单线程或多线程(使用 openmp)执行 for 所花费的时间,因此我编写了以下代码来查看差异:

#define N 1000000000 // 10^9

int main(int argc, char* argv[])
{
int i, *a = malloc(N * sizeof *a);
clock_t begin, end;
double time_spent;

begin = clock();

#pragma omp parallel for
for(i=0;i<N;i++)
a[i] = i;

end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time Spent: %lf\n", time_spent);
free(a);
return 0;
}

但是奇怪的事情发生了:#pragma规则时,执行时间约为4.6s,但没有规则时,执行时间约为3.6s。怎么可能呢?难道我做错了什么?或者也许我没有使用正确的计时功能?

最佳答案

clock() 返回CLOCK_PROCESS_CPUTIME_ID时钟的值。该时钟在clock_gettime(3)中描述:

CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12)
Per-process CPU-time clock (measures CPU time consumed by all
threads in the process).

clock_gettime()CLOCK_MONOTONIC结合使用以获得正确的测量结果。

关于c - 并行执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35171628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com