In python, vectorization speeds things up because it allows the use of numpy. In julia, this isn’t necessary.
Python:
import numpy as np
from time import time
x = np.random.rand(10**7)
y = np.random.rand(10**7)
def vectorized(x, y):
return x*x + y*y + x*y
def loop(x, y):
[x*x + y*y + x*y for (x,y) in zip(x,y)]
t0 = time()
vectorized(x,y) # 0.24799013137817383
t1 = time()
vectorized(x,y) # 0.09563016891479492
t2 = time()
print(t1-t0)
print(t2-t1)
t0 = time()
loop(x,y) # 4.1851279735565186
t1 = time()
loop(x,y) # 4.027431964874268
t2 = time()
print(t1-t0)
print(t2-t1)
Juila:
x = rand(10^7)
y = rand(10^7)
vectorized(x, y) = x.*x .+ y.*y .+ x.*y
loop(x, y) = [x*x + y*y + x*y for (x,y) in zip(x,y)]
@time vectorized(x,y)
# 0.216033 seconds (462.89 k allocations: 99.817 MiB, 2.25% gc time, 50.76% compilation time)
@time vectorized(x,y)
# 0.189564 seconds (2 allocations: 76.294 MiB)
@time loop(x,y)
# 0.139699 seconds (300.01 k allocations: 92.649 MiB, 46.57% compilation time)
@time loop(x,y)
# 0.122678 seconds (2 allocations: 76.294 MiB)