Created
January 16, 2023 13:05
-
-
Save luizdepra/c576d845937dfd1215b59cf2a7b428cf to your computer and use it in GitHub Desktop.
Python List Allocation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from functools import wraps | |
from time import time | |
@dataclass | |
class Thing: | |
pass | |
def timed(f): | |
@wraps(f) | |
def wrap(*args, **kw): | |
ts = time() | |
result = f(*args, **kw) | |
te = time() | |
print(f'func:{f.__name__} args:[{args}, {kw}] took: {te-ts:.08f} sec') | |
return result | |
return wrap | |
@timed | |
def create_matrix(width, height): | |
result = [] | |
for _ in range(height): | |
for _ in range(width): | |
result.append(Thing()) | |
return result | |
@timed | |
def create_matrix_with_listcomp(width, height): | |
return [[Thing() for _ in range(width)] for _ in range(height)] | |
@timed | |
def create_prealloc_matrix(width, height): | |
result = [None] * height | |
for j in range(height): | |
result[j] = [None] * width | |
for j in range(height): | |
for i in range(width): | |
result[j][i] = Thing() | |
return result | |
@timed | |
def create_array(width, height): | |
result = [] | |
for _ in range(width*height): | |
result.append(Thing()) | |
return result | |
@timed | |
def create_array_with_listcomp(width, height): | |
return [Thing() for _ in range(width*height)] | |
@timed | |
def create_prealloc_array(width, height): | |
result = [None] * width * height | |
for i in range(width * height): | |
result[i] = Thing() | |
return result | |
def main(): | |
create_matrix(100, 100) | |
create_matrix_with_listcomp(100, 100) | |
create_prealloc_matrix(100, 100) | |
create_array(100, 100) | |
create_array_with_listcomp(100, 100) | |
create_prealloc_array(100, 100) | |
if __name__ == '__main__': | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func:create_matrix args:[(100, 100), {}] took: 0.00401878 sec | |
func:create_matrix_with_listcomp args:[(100, 100), {}] took: 0.00277829 sec | |
func:create_prealloc_matrix args:[(100, 100), {}] took: 0.00284767 sec | |
func:create_array args:[(100, 100), {}] took: 0.00486350 sec | |
func:create_array_with_listcomp args:[(100, 100), {}] took: 0.00380182 sec | |
func:create_prealloc_array args:[(100, 100), {}] took: 0.00343609 sec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment