Fortran Coder
标题: 为什么多线程并行速度会比单线程慢很多? [打印本页]
作者: RZND010 时间: 2017-7-28 13:09
标题: 为什么多线程并行速度会比单线程慢很多?
代码如下:
[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode
program main
implicit real*8 (a-z)
include 'omp_lib.h'
integer i
integer,parameter :: s=320000
open(1,file='./epf.dat')
call cpu_time(t1)
call omp_set_num_threads(4)
!$OMP PARALLEL DO PRIVATE(epf,nobs)
do i=1,s
epf=2.0*i
nobs=epf**2
write(1,*) nobs,epf
end do
!$OMP END PARALLEL DO
call cpu_time(t2)
write(*,*) t2-t1
end
测试发现多线程会比单线程慢很多,而且线程越多越慢。
作者: fcode 时间: 2017-7-28 19:04
我的理解:
1. 并行结构最好不要包含输入输出语句,因为它们并不具有可并行性能。
2. CPU_TIME在并行结构中会重复计算,并不是真实的物理挂钟时间。你占用4个线程,每个·1秒,则cpu_time就是4秒,即使真实物理时间只过了1秒。
所以,如下是一个更好的测试程序。
[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode
program main
implicit none
include 'omp_lib.h'
integer i
integer,parameter :: s=3200000
integer :: t1 , t2
real :: epf , nobs
open(1,file='./epf.dat')
call system_clock(t1)
call omp_set_num_threads(4)
!$OMP PARALLEL DO PRIVATE(epf,nobs)
do i=1,s
epf=2.0*i
nobs=epf**2
end do
!$OMP END PARALLEL DO
call system_clock(t2)
write(*,*) t2-t1
end
作者: RZND010 时间: 2017-7-29 09:54
对,我昨天发完贴就发现这个问题了,我也用的system_clock计算时间,但好像计算出来的也不大对。。。不过比用cpu_time好
作者: RZND010 时间: 2017-7-29 09:59
多线程好像不能同时打开一个文件,我输出是先用一个数组保存数据,在循环外write。
谢谢了!
作者: 维尼猴 时间: 2017-7-29 10:53
学习了!
作者: redasia 时间: 2017-11-23 17:50
我将这段代码复制到一个console程序里面,却无法运行,不知何故,出现以下错误:
错误 1 error LNK2019: 无法解析的外部符号 _omp_set_num_threads,该符号在函数 _MAIN__ 中被引用
作者: Jackdaw 时间: 2017-11-25 11:28
[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode
program main
use omp_lib
implicit none
integer :: i
call omp_set_num_threads(5)
!$omp parallel private(i)
i = omp_get_thread_num()
write(*,*) "Hello, Fortran Coder. from thread.",i
!$omp end parallel
write(*,*)
call omp_set_num_threads(3)
!$omp parallel private(i)
i = omp_get_thread_num()
write(*,*) "Hello, Fortran Coder. from thread.",i
!$omp end parallel
end program main
作者: Jackdaw 时间: 2017-11-25 11:30
检查是否打开支持OpenMP选项
作者: redasia 时间: 2017-11-30 16:48
是的,Project Property->Fortran->Process OpenMP Directives>disable改掉,就可以了。
欢迎光临 Fortran Coder (http://bbs.fcode.cn/) |
Powered by Discuz! X3.2 |