Julia Community 🟣

Vinod V
Vinod V

Posted on • Edited on

Boosting Julia Performance: Benchmarking Code in Function, Global Scope, and Builtin

Julia's code execution efficiency can vary depending on where the code is executed. The two possible locations are the local scope and the global scope.Alternatively, we can use the builtin function. To compare the efficiency of code execution in these two locations, we can use the BenchmarkTools module in Julia. For instance, consider the following code snippet that calculates the total of an array in global , local scopes and builtin. The profiling results indicate that the local scope code is more efficient in terms of execution time than the global scope code But the builtin code is most efficient (probably Julia is using the formula n(n+1)/2 to sum first n integers).

using BenchmarkTools

i = 1
total = 0

function sum1(num) #global scope
global i
global total
    for i in eachindex(num)
        total += num[i]
    end
    return total
end

function sum2(num) #local scope
    total = 0
    for i in eachindex(num)
        total += num[i]
    end
    return total
end

#a = rand(1:1000,1,10000)
a = 1:100000

println("sum1")
@btime b = sum1($a)
println("Sum2")
@btime b = sum2($a)
println("Builtin sum")
@btime b = sum($a)

sum1
  3.136 ms (199489 allocations: 3.04 MiB)
Sum2
  55.498 μs (0 allocations: 0 bytes)
Builtin sum
  0.001 ns (0 allocations: 0 bytes)
5000050000
Enter fullscreen mode Exit fullscreen mode

Discussion here https://discourse.julialang.org/t/why-the-function-sum1-is-faster-than-builtin-sum/104051/12

Top comments (0)