0

Why is numpy slower in this code?

for i in range(10000):
    array = [[0.0,] * 1024 for x in range(1024)]

0,021539204 seconds time elapsed (39.616.810 instructions)

import numpy as np
for i in range(10000):
    array = np.zeros((1024,1024))

0.209111860 seconds time elapsed (1.067.923.180 instructions)

amrs-tech
  • 485
  • 2
  • 14
Chariot
  • 335
  • 1
  • 3
  • 13
  • `array = [[0.0,] * 1024 for x in range(1024)]` doesn't give you an array, it gives you a list – roganjosh Sep 20 '19 at 12:10
  • 1
    If you used `timeit` rather than shoving it in a loop, you'd get `7.4 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)` for the Python list and `11.2 µs ± 137 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)` for the numpy approach. The timings in your approach are completely flawed because the python `for` loop dominates – roganjosh Sep 20 '19 at 12:17
  • numpy is faster than list. Even you can perform their performance in this link: https://webcourses.ucf.edu/courses/1249560/pages/python-lists-vs-numpy-arrays-what-is-the-difference . Check using timeit will help you to know more. Thanks :) – Sapan Zaveri Sep 20 '19 at 13:01

1 Answers1

3

Are you running in the exact same machine? I'm getting faster result in numpy.

In [7]: %%time
   ...: import numpy as np
   ...: for i in range(10000):
   ...:     array = np.zeros((1024,1024))
   ...:
CPU times: user 3.33 s, sys: 0 ns, total: 3.33 s
Wall time: 3.32 s

In [8]: %%time
   ...: for i in range(10000):
   ...:     array = [[0.0,] * 1024 for x in range(1024)]
   ...:
CPU times: user 1min 14s, sys: 0 ns, total: 1min 14s
Wall time: 1min 14s

This answer in the numpy vs list thread also agrees.

Darren Christopher
  • 3,893
  • 4
  • 20
  • 37