Skip to content

Instantly share code, notes, and snippets.

@GoodManWEN
Last active March 31, 2021 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GoodManWEN/dc9372c7a0288837aa4ffd4b0ddc85f8 to your computer and use it in GitHub Desktop.
Save GoodManWEN/dc9372c7a0288837aa4ffd4b0ddc85f8 to your computer and use it in GitHub Desktop.
numpy array vs native
import numpy as np
import inspect
import time
class timeit:
def __init__(self, name=""):
self.st_time = 0
self.display_name = f'[{name}] ' if name != '' else f'[line {inspect.stack()[1].lineno}] '
def __enter__(self):
self.st_time = time.time()
return self
def __exit__(self,exc_type,exc_val,exc_tb):
print(f"{self.display_name}time cost: {time.time() - self.st_time}")
if exc_val:
raise exc_val
ARRAY_SIZE = 100000
n1 = np.zeros(ARRAY_SIZE,dtype=np.int_)
with timeit():
for i in range(10000):
n1 += 2
print(n1)
n2 = [0 for _ in range(ARRAY_SIZE)]
with timeit():
for i in range(100):
for j in range(ARRAY_SIZE):
n2[j] += 2
print(n2[:5])
'''
Output:
[line 21] time cost: 0.3201007843017578
[20000 20000 20000 ... 20000 20000 20000]
[line 28] time cost: 0.7021913528442383
[200, 200, 200, 200, 200]
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment