在同一时间执行多个进程时速度急剧减慢

2024-09-27 21:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Fortran和Python编写了一个非常简单的代码,其中包含数组的求和。当我使用shell提交多个(独立的)作业时,当线程数大于一个时,速度会急剧减慢。你知道吗

我的代码的Fortran版本如下

program main
implicit none
real*8 begin, end, Ht(2, 2), ls(4)
integer i, j, k, ii, jj, kk
integer,parameter::N_tiles = 20
integer,parameter::N_tilings = 100
integer,parameter::max_t_steps = 50
real*8,dimension(N_tiles*N_tilings,max_t_steps,5)::test_e, test_theta
real*8 rand_val

call random_seed()
do i = 1, N_tiles*N_tilings
  do j = 1, max_t_steps
    do k = 1, 5
      call random_number(rand_val)
      test_e(i, j, k) = rand_val
      call random_number(rand_val)
      test_theta(i, j, k) = rand_val
    end do
  end do
end do

call CPU_TIME(begin)
do i = 1, 1001
  do j = 1, 50
    test_theta = test_theta+0.5d0*test_e
  end do
end do
call CPU_TIME(end)

write(*, *) 'total time cost is : ', end-begin

end program main

并且shell-scipt呈现如下

#!/bin/bash
gfortran -o result test.f90

nohup ./result &
nohup ./result &
nohup ./result &

我们可以看到,主要的操作是数组test_thetatest_e的求和。这些阵列不是很大(大约3MB),我的计算机的内存空间足以完成这项工作。我的工作站有6个内核和12个线程。我尝试使用shell一次性提交1、2、3、4和5个作业,时间成本如下所示

| #jobs   |  1   |   2   |   3    |  4    |  5   |
| time(s) |  21  |   31  |   161  |  237  |  357 | 

我希望n线程作业的时间应该与单线程作业的时间相同,只要线程数小于我们拥有的内核数(这里是我的计算机的6个)。然而,我们在这里发现了戏剧性的减速。你知道吗

当我使用Python实现相同的任务时,这个问题仍然存在

import numpy as np 
import time

N_tiles = 20
N_tilings = 100
max_t_steps = 50
theta = np.ones((N_tiles*N_tilings, max_t_steps, 5), dtype=np.float64)
e = np.ones((N_tiles*N_tilings, max_t_steps, 5), dtype=np.float64)

begin = time.clock()

for i in range(1001):
    for j in range(50):
        theta += 0.5*e

end = time.clock()
print('total time cost is {} s'.format(end-begin))

我不知道原因,我想知道这是否与CPU的三级缓存的大小有关。也就是说,缓存对于这样的多线程作业来说太小了。或许也与所谓的“虚假分享”问题有关。我怎样才能解决这个问题?你知道吗

这个问题与前一个问题dramatic slow down using multiprocess and numpy in python有关,这里我只发布了一个简单而典型的例子。你知道吗


Tags: testtimenp作业valcallstepsdo
1条回答
网友
1楼 · 发布于 2024-09-27 21:33:31

代码在多次运行时可能很慢,因为必须通过有限带宽内存总线的内存越来越多。你知道吗

如果您只运行一个进程,一次只运行一个阵列,但启用OpenMP线程,则可以使其更快:

integer*8 :: begin, end, rate
...

call system_clock(count_rate=rate)
call system_clock(count=begin)

!$omp parallel do
do i = 1, 1001
  do j = 1, 50
    test_theta = test_theta+0.5d0*test_e
  end do
end do
!$omp end parallel do

call system_clock(count=end)
write(*, *) 'total time cost is : ', (end-begin)*1.d0/rate

在四核CPU上:

> gfortran -O3 testperformance.f90 -o result
> ./result 
 total time cost is :    15.135917384000001
> gfortran -O3 testperformance.f90 -fopenmp -o result
> ./result 
 total time cost is :    3.9464441830000001

相关问题 更多 >

    热门问题