Domanda

I have the following example in Python:

import numpy as np
import timeit

# array size
m = 3000

# square array
a = np.random.rand(m, m)

# column vector
b = np.random.rand(m)

# solve
ti = timeit.default_timer()
x = np.linalg.solve(a, b)
tf = timeit.default_timer()

# solve function
def solver(a, b):
    x = np.linalg.solve(a, b)
    return x

tii = timeit.default_timer()
x = solver(a, b)
tff = timeit.default_timer()

print('time1 ', tf-ti)
print('time2 ', tff-tii)

The time comparison for not using a function (time1) vs using a function (time2) is:

time1  0.6199771239989786
time2  0.5945519460001378

There seems to be a slight difference between in the two approaches. How are the input parameters handled for the function solver, are they copied or are they just passed to the internals of the function?

È stato utile?

Soluzione

The speed difference is likely due to some memory caching of the contents of a and b that the second call to linalg.solve takes advantage of.

And to answer the question, objects in python are passed by reference, so the only differencein the cost of passing arguments is that you are doing it twice in the 2nd example. But that is probably a tiny fraction of the solve cost.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top