r/Julia • • Jul 22 '21

Julia nested array comprehension being more than 2X SLOWER than Python's nested list comprehension counterpart. Tips on how to optimize/speed this up?

So I have a 3D function that I want to make a contour/surface plot of originally in Python, which involves the Gauss error function:

from numpy import *
from scipy.integrate import quad
dps = 301 #number of data points
x = linspace(0, 3, dps)
t = linspace(1, 2.592e7, dps)
Ti, Ts, alpha = 12, -15, 0.138e-6
def T(x,t):
    erf = lambda x: quad(lambda u: exp(-u**2), 0, x)[0]
    expr = Ts + (Ti-Ts)*2/sqrt(pi)*erf( x / ( 2*sqrt(alpha*t) ) )
    return expr
z = array([ [ T(i,j) for i in x ] for j in t ])

Because of the error function where the independent variable is the upper bound of the integral, I am forced to use a nested list comprehension to generate my z values as shown from above and this is where the problem starts. I would like to have a dense contour/surface plot, with the number of data points being at least 1001, but I realized that the reason why Python is being slow with this even if I just gave it 301 points is because the number of iterations being performed is the number of data points squared. 301 points mean 90601 iterations and 1001 data points mean 1002001 iterations, well over a million already!

I tried speeding this up with numba, but the resulting function after applying njit() doesn't perform any better than standard Python so I decided to try this in Julia:

using PyCall
si = pyimport("scipy.integrate")
dps = 301 #number of data points
x = LinRange(0, 3, dps)
t = LinRange(1, 2.592e7, dps)
Ti, Ts, alpha = 12, -15, 0.138e-6
function T(x,t):
    erf = x-> si.quad(u->exp(-u^2), 0, x)[1]
    expr = Ts + (Ti-Ts)*2/sqrt(pi)*erf( x / ( 2*sqrt(alpha*t) ) )
    return expr
z = [ T(i,j) for i=x, j=t ]

The resulting performance is palpably worse in Julia than in Python. For dps = 301, the execution speed in Python as timed with %time z = array([ [ T(i,j) for i in x ] for j in t ]) is 7.5-8 seconds while Julia's execution speed as timed with:

 @time begin
z = [ T(i,j) for i=x, j=t ]
end;

is 18-20 seconds. This is the case even if I broadcast the function with T.(x,t') .

Could this be because I'm using scipy's quad function that makes it so slow? I expected Julia to be faster especially because the documentation for Julia says that we don't need to vectorize our code to make it fast. When I have a normal Julia function like f(x,y) = x*log(y+1) and I evaluate and time it over a meshgrid of points using Julia's broadcast mechanism as in the following:

x = LinRange(-10, 10, 1001)
y = LinRange(0, 10,1001)
@time begin
f.(x,y')
end

the execution speeds after compilation is at most 7 milliseconds.

Edit:

  1. Replacing SciPy's quad function with quadgk from from QuadGK.jl already makes the code way faster and more bearable. It takes around 3 seconds to generate the z values for 2001 data points with this change, in contrast in Python it can barely manage 1001 data points.

  2. In addition to what the others suggested about using SpecialFunctions.jl's erf function, it actually turns out that, upon google-searching, there is also an erf function from SciPy in scipy.special that is able to take input arrays (Python's math also has an erf function, but it can't take arrays as input). So that makes either quad or quadgk not needed anymore and I actually could feasibly and easily make dense contour/surface plots for this problem even in Python.

6 Upvotes

26 comments sorted by

51

u/pLOPeGG Jul 22 '21 edited Jul 22 '21

Why would you expect better result in Julia calling python than directly in python ? You better find a quad equivalent in Julia and then broadcast over the meshgrid.

I'm not and expert in scipy but isn't QuadGK.jl equivalent to quad ?

7

u/[deleted] Jul 22 '21 edited Jul 23 '21

I didn't expect the calculations to get slowed down in Julia due to using SciPy's quad function because SciPy's quad function was faster than my own newton-cotes formulas that I coded and implemented (in Python, I might add). They struggled in one problem that I gave/used them on while SciPy's quad function solved it within a second.

Anyway, I tried QuadGK as you said and it only takes a few seconds to generate the z values for 2001 points, in contrast for one whole minute in Python for 1001 points. When I tried 2001 points in Python, my laptop crashed.

9

u/tending Jul 23 '21

Inter language communication has its own high overhead, separate from the regular cost of actually running a given function.

2

u/[deleted] Jul 23 '21

Yeah, I see. Learned it the hard way.

4

u/TheSodesa Jul 23 '21

The reason a lot of Python library functions are so fast is that they are actually written in C. CPython (the standard Python implementation) has very good interoperability with C by design:

https://docs.python.org/3/extending/extending.html

Note that Python is a slower language than C, so in this case calling SciPy functions from Python is doing the opposite of what you were trying with Julia and Python.

2

u/[deleted] Jul 23 '21

Thanks! This is quite informative and useful. I learned a lot.

47

u/TheSodesa Jul 22 '21 edited Jul 22 '21

If you want to take advantage of the speed boost Julia has over Python, you will need to convert all of your Python code to pure Julia. Calling the Python interpreter via Julia is not going to magically make your code any faster, because you are still running the Python code through the same Python interpreter.

The added slowdown when compared to pure Python is caused by Julia having to negotiate with the Python interpreter. If you want to use Python, just stick to Python.

Edit: As a general note, there is no point in calling a slower language from a faster language, unless the slower language contains functionality that is either unavailable or unpractically hard to implement in the faster language. That is not the case here, however.

11

u/[deleted] Jul 22 '21

Thanks, I guess that actually makes sense. I didn't expect the more than 2x slow down since quad is just the only one being called from Python. I replaced SciPy's quad with quadgk from QuadGK.jl and it's already several orders of magnitude faster now since it only takes around 3 seconds to generate the z values for 2001 data points while Python can barely manage 1001 points and my laptop crashed when trying 2001 data points.

I guess that although Julia is relatively young compared to Python, I may be underestimating the maturity of the Julia ecosystem too.

16

u/lungben81 Jul 22 '21

Ti, Ts, alpha = 12, -15, 0.138e-6

You should avoid using global variables, see here: https://docs.julialang.org/en/v1/manual/performance-tips/#Avoid-global-variables

Plus, as stated below, do not use Python functions in a Julia hot loop but its Julia equivalence.

4

u/[deleted] Jul 22 '21

Thanks! This is nice and I get now why I should avoid using them and to annotate their type when using non-constant global variables.

5

u/lungben81 Jul 22 '21

I think in your case it is best to make a parameter struct, e.g. using `Base.@kwdef`, which you pass as a parameter to your function. Make sure that all properties of the parameter struct are concretely typed (or have type parameters).

2

u/[deleted] Jul 22 '21

I'm still not intimately familiar with these unique-to-Julia features, specifying types or structs, all that---it's among the many goals I planned out to learn Julia's programming basics by itself and don't think about the numerical computation aspect for a while---but I guess that would be the equivalent of *args in Python that will unpack the iterables as argument functions, though there might not be as much need to avoid global variables in Python compared to Julia.

5

u/lungben81 Jul 22 '21

Funnily, global variables are also slower in Python, compared to passing the data as function parameters. But the difference is only ~20% compared to up to a factor of 100 in Julia.

A Julia struct is similar to a class in Python, except that the methods are defined outside, not inside a class. The most similar thing to a Julia struct is a Python DataClass.

6

u/gipp Jul 22 '21

Other points aside:

def T(x,t):
    erf = lambda x: quad(lambda u: exp(-u**2), 0, x)[0]

Since you're shadowing x in the declaration of erf, this is declaring the exact same erf function over and over for every point, which is pure overhead. You could move that declaration outside of T. Or better yet just use a library erf.

2

u/[deleted] Jul 22 '21

Thanks! This is quite useful and insightful. I thought that I was being "concise" putting the error function inside of it, simply copying the equation straight out of the book. I'll keep that in mind always.

0

u/[deleted] Jul 22 '21

[deleted]

2

u/[deleted] Jul 22 '21

A library erf is still recommended because it's probably going to be more efficient and accurate than a general integration method, and because it's not calling julia through python through julia for every single point.

Indeed, and SciPy quite thankfully turns out that it has its own implementation of erf with scipy.special.erf, which allows me to easily make the dense plot I need in Python itself. I've been plotting with plotly.graph_objects/plotly.express have very extensive and comprehensive documentation compared to Plots.jl, which makes it hard to let go of.

3

u/gipp Jul 22 '21

Yes, this was more aimed at the Python implementation. I'm much less familiar with Julia and JIT details.

12

u/briochemc Jul 22 '21
using SpecialFunctions, BenchmarkTools
dps = 301 #number of data points
x = range(0, 3, length=dps)
t = range(1, 2.592e7, length=dps)
const Ti, Ts, α = 12, -15, 0.138e-6
T(x,t) = Ts + 2(Ti - Ts) / sqrt(π) * erf(x / 2sqrt(α * t))
@btime z = [T(i,j) for i in $x, j in $t]

takes merely a few milliseconds for me

2

u/backtickbot Jul 22 '21

Fixed formatting.

Hello, briochemc: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

-1

u/ndgnuh Jul 22 '21

How to receive a lot of reply:

Julia <something> being nX SLOWER than <something> counterpart, how to optimize/speed this up?

xD

0

u/[deleted] Jul 22 '21

[deleted]

3

u/[deleted] Jul 22 '21

Yes, you're right. And it actually turns out that SciPy has its own implementation of the erf function in scipy.special.erf so even in Python, I should've not had a hard time with this had I discovered it earlier. I just google-searched a while ago if Python had an implementation for the error function because I couldn't stand that I wouldn't be able to make dense plots for this one in Python because plotly.graph_objects is just too good, powerful, and very well documented in the Plotly documentation for Python compared to Plots.jl.

4

u/oscardssmith Jul 22 '21

Yeah. Actually using a good erf implimentation will likely be around 100x faster.

2

u/[deleted] Jul 22 '21

As is the case with most functions that are implemented in the many libraries. The SciPy implementation of the Dormand-Prince5(4) algorithm, for example, is faster than my own implementation and integrates with fewer points than mine.

9

u/oscardssmith Jul 22 '21

The good implimentations of erf don't integrate at all. They use a polynomial approximations (often combined with rescaling by exp(x2) ). This approach is both significantly more accurate and significantly faster than numeric integration.

2

u/[deleted] Jul 22 '21

Ohh I see. That's quite interesting thing to know about.

11

u/jammacus Jul 22 '21

Yes, in general try to avoid calling python where possible as I believe there's quite a bit of overhead involved