如何提高这段代码的性能? [英] How to improve the performance of this piece of code?

查看:62
本文介绍了如何提高这段代码的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习一些朱莉娅,在阅读了几个小时的手册之后,我编写了以下代码:

I'm trying to learn a bit of Julia, after reading the manual for several hours, I wrote the following piece of code:

ie = 200;
ez = zeros(ie + 1);
hy = zeros(ie);

fdtd1d (steps)=
    for n in 1:steps
        for i in 2:ie
            ez[i]+= (hy[i] - hy[i-1])
        end
        ez[1]= sin(n/10)
        for i in 1:ie
            hy[i]+= (ez[i+1]- ez[i])
        end
    end

@time fdtd1d(10000);

 elapsed time: 2.283153795 seconds (239659044 bytes allocated)

我认为它正在优化中,因为它比相应的 Mathematica 版本要慢得多:

I believe it's under optimizing, because it's much slower than the corresponding Mathematica version:

ie = 200;
ez = ConstantArray[0., {ie + 1}];
hy = ConstantArray[0., {ie}];

fdtd1d = Compile[{{steps}}, 
   Module[{ie = ie, ez = ez, hy = hy}, 
    Do[ez[[2 ;; ie]] += (hy[[2 ;; ie]] - hy[[1 ;; ie - 1]]);
     ez[[1]] = Sin[n/10];
     hy[[1 ;; ie]] += (ez[[2 ;; ie + 1]] - ez[[1 ;; ie]]), {n, 
      steps}]; Sow@ez; Sow@hy]];

result = fdtd1d[10000]; // AbsoluteTiming

{0.1280000, Null}

那么,如何使fdtd1d的Julia版本更快?

So, how to make the Julia version of fdtd1d faster?

推荐答案

两件事:

第一次运行该函数时,该时间将包括代码的编译时间.如果您希望使用Mathematica中的编译函数进行比较,则应两次运行该函数并为第二次运行计时.使用您的代码,我得到:

The first time you run the function the time will include the compile time of the code. If you want a apples to apples comparison with a compiled function in Mathematica you should run the function twice and time the second run. With your code I get:

elapsed time: 1.156531976 seconds (447764964 bytes allocated)

首次运行,其中包括编译时间和

for the first run which includes the compile time and

elapsed time: 1.135681299 seconds (447520048 bytes allocated)

不需要编译的第二次运行.

for the second run when you don't need to compile.

第二件事,可以说是更大的事情,是应该避免在性能关键代码中使用全局变量.这是手册.

The second thing, and arguably the bigger thing, is that you should avoid global variables in performance critical code. This is the first tip in the performance tips section of the manual.

以下是使用局部变量的相同代码:

Here is the same code using local variables:

function fdtd1d_local(steps, ie = 200)
    ez = zeros(ie + 1);
    hy = zeros(ie);
    for n in 1:steps
        for i in 2:ie
            ez[i]+= (hy[i] - hy[i-1])
        end
        ez[1]= sin(n/10)
        for i in 1:ie
            hy[i]+= (ez[i+1]- ez[i])
        end
    end
    return (ez, hy)
end

fdtd1d_local(10000)
@time fdtd1d_local(10000);

要在您的计算机上比较您的Mathematica代码

To compare your Mathematica code on my machine gives

{0.094005, Null} 

,而@time对于fdtd1d_local的结果是:

elapsed time: 0.015188926 seconds (4176 bytes allocated)

或快大约6倍.全局变量有很大的不同.

Or about 6 times faster. Global variables make a big difference.

这篇关于如何提高这段代码的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆