【发布时间】:2018-09-22 01:15:34
【问题描述】:
我正在尝试从 https://github.com/joeladams/patternlets/blob/master/patternlets/openMP/14.mutualExclusion-critical2/critical2.c 证明关键是更耗时,但我不断得到关键的执行时间比原子更快的结果。有谁知道这是怎么回事?
// simulate many deposits using atomic
startTime = omp_get_wtime();
#pragma omp parallel for
for (i = 0; i < REPS; i++) {
#pragma omp atomic
balance += 1.0;
}
stopTime = omp_get_wtime();
atomicTime = stopTime - startTime;
print("atomic", REPS, balance, atomicTime, atomicTime/REPS);
// simulate the same number of deposits using critical
balance = 0.0;
startTime = omp_get_wtime();
#pragma omp parallel for
for (i = 0; i < REPS; i++) {
#pragma omp critical
{
balance += 1.0;
}
}
stopTime = omp_get_wtime();
criticalTime = stopTime - startTime;
print("critical", REPS, balance, criticalTime, criticalTime/REPS);
我的结果是:
After 1000000 $1 deposits using 'atomic':
- balance = 1000000.00,
- total time = 0.421999931335,
- average time per deposit = 0.000000422000
After 1000000 $1 deposits using 'critical':
- balance = 0.00,
- total time = 0.265000104904,
- average time per deposit = 0.000000265000
谢谢!
【问题讨论】:
-
执行第一次不定时并行计算,以便在两种情况下都准备好 OpenMP 线程。
-
在我的例子中:wandbox.org/permlink/mxL9fAVWIycEHlVN,即使有线程创建开销,原子也更快。请注意,您的代码有问题,因为
balance在第二次循环之后是0.00,因此增量不适用。 -
请始终将您的代码发布为minimal reproducible example!
标签: c++ c openmp atomic critical-section