General questions from Python user

It can sometimes carry a higher cost in julia however.

If you’d like an example, here’s an example from this thread:

In [6]: def euclidian_algorithm_division_count(a, b):
   ...:     division_count = 1
   ...:     if b > a:
   ...:         a, b = b, a
   ...:     while (c := a % b) != 0:
   ...:         a, b = b, c
   ...:         division_count += 1
   ...:     return division_count
   ...: 
   ...: from random import randint

In [7]: %%timeit
   ...: N = 10**100
   ...: M = 10**4
   ...: division_count_array = []
   ...: while M > 0:
   ...:     a = randint(1, N)
   ...:     b = randint(1, N)
   ...:     division_count_array.append(euclidian_algorithm_division_count(a, b))
   ...:     M -= 1
292 ms ± 7.74 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
julia> function euclidean_algorithm_division_count(a, b)
           division_count = 1
           if b > a
               a, b = b, a
           end
           while (c = a % b) != 0
               a, b = b, c
               division_count += 1
           end
           return division_count
       end
euclidean_algorithm_division_count (generic function with 1 method)

julia> function main()
           N = big(10)^100
           M = 10^4
           division_count_array = []
           while M > 0
               a, b = rand(1:N, 2)
               push!(division_count_array, euclidean_algorithm_division_count(a, b))
               M -= 1
           end
       end
main (generic function with 1 method)

julia> @btime main()
  378.040 ms (5618922 allocations: 110.55 MiB)

It’s of course not very hard to make the julia version beat the Python version, but this straightforward transcription (that even uses a function) of naive Python code can still be slower in julia.

2 Likes