John
John

Reputation: 527

Any benefits to importing sub modules directly (seems to be slower)?

I wanted to see which is faster:

import numpy as np
np.sqrt(4)

-or-

from numpy import sqrt
sqrt(4)

Here is the code I used to find the average time to run each.

def main():
   import gen_funs as gf
   from time import perf_counter_ns
   t = 0
   N = 40
   for j in range(N):
      tic = perf_counter_ns()
      for i in range(100000):
         imp2()  # I ran the code with this then with imp1()

      toc = perf_counter_ns()
      t += (toc - tic)
   t /= N
   time = gf.ns2hms(t) # Converts ns to readable object
   print("Ave. time to run: {:d}h {:d}m {:d}s {:d}ms" .
        format(time.hours, time.minutes, time.seconds, time.milliseconds))

def imp1():
   import numpy as np
   np.sqrt(4)
   return

def imp2():
   from numpy import sqrt
   sqrt(4)
   return

if __name__ == "__main__":
   main()

When I import numpy as np then call np.sqrt(4), I get an average time of about 229ms (time to run the loop 10**4 times).

When I run from numpy import sqrt then call sqrt(4), I get an average time of about 332ms.

Since there is such a difference in time to run, what is the benefit to running from numpy import sqrt? Is there a memory benefit or some other reason why I would do this?

Upvotes: 0

Views: 47

Answers (1)

101arrowz
101arrowz

Reputation: 1905

I tried timing with the time bash command. I got 215ms for importing numpy and running sqrt(4) and 193ms for importing sqrt from numpy with the same command. The difference is negligible, honestly.

However, if you don't need a certain aspect of a module, importing it is not encouraged.

In this particular case, since there is no discernable performance benefit and because there are few situations in which you would import just numpy.sqrt (math.sqrt is ~4x faster. The extra features numpy.sqrt offers would only be useable if you have numpy data, which would require you to import the entire module, of course).

There might be a rare scenario in which you don't need all of numpy but still need numpy.sqrt, e.g. using pandas.DataFrame.to_numpy() and manipulating the data in some ways, but honestly I don't feel the 20ms of speed is worth anything in the real world. Especially since you saw worse performance with importing just numpy.sqrt.

Upvotes: 1

Related Questions