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)

3
  • array = [[0.0,] * 1024 for x in range(1024)] doesn't give you an array, it gives you a list Commented Sep 20, 2019 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 Commented Sep 20, 2019 at 12:17
  • numpy is faster than list. Even you can perform their performance in this link: webcourses.ucf.edu/courses/1249560/pages/… . Check using timeit will help you to know more. Thanks :) Commented Sep 20, 2019 at 13:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.