Identifying type-unstable functions

In Julia, there is no need to specify the type of variables. In fact, to be more precise, variables are not typed. Variables are merely bindings to values, and values are typed. That is what makes Julia programs dynamic. However, such flexibility comes with a cost. Because the compiler must generate code that supports all possible types that may come up during runtime, it is unable to generate optimized code. 

Consider a simple function that just returns an array of random numbers:

random_data(n) = isodd(n) ? rand(Int, n) : rand(Float64, n)

If the n argument is odd, then it returns an array of random Int values. Otherwise, it returns an array of random Float64 values.

This innocent function is actually type-unstable. We can use the @code_warntype facility to check:

The @code_warntype macro displays an Intermediate Representation (IR) of the code. An IR is generated by the compiler after it understand the flow and data type of every line in that code. For our purpose here, we do not need to understand everything printed on screen but we can pay attention to the highlighted text as related to the data types generated from the code. In general, when you see red text, it would also be a red flag.

In this case, the compiler has figured that the result of this function can be an array of Float64 or an array of Int64. Hence, the return type is just Union{Array{Float64,1}, Array{Int64,1}}.

In general, more red signs from the @code_warntype output indicates more type instability problems in the code.

The function does exactly what we want to do. But when it's used in the body of another function, the type instability problem further affects runtime performance. We can use a barrier function to solve this problem.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.72.78