Created
August 24, 2017 08:32
-
-
Save kshitij10496/8e99d6dd4c287a3e0a77a184be6e7924 to your computer and use it in GitHub Desktop.
Performance comparison of Iteration and Generators
This file contains 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 memory_profiler import profile | |
import random | |
import hug | |
@profile | |
def random_list(quantity): | |
result = [] | |
for i in range(1, quantity+1): | |
result.append((i, random.randint(0, 9))) | |
return result | |
@profile | |
def random_list_comprehension(quantity): | |
return [(i, random.randint(0, 9)) for i in range(1, quantity+1)] | |
@profile | |
def random_list_generator(quantity): | |
for i in range(1, quantity+1): | |
yield (i, random.randint(0,9)) | |
@profile | |
def random_list_generator_expression(quantity): | |
return ((i, random.randint(0, 9)) for i in range(1, quantity+1)) | |
@hug.cli() | |
def cli(quantity: hug.types.number): | |
random_list(quantity) | |
print('Profile random_list called:') | |
print('===================================================================') | |
random_list_comprehension(quantity) | |
print('Profile random_list_comprehension called:') | |
print('===================================================================') | |
print('Profile random_list_generator:', random_list_generator(quantity)) | |
print('===================================================================') | |
print('Profile random_list_generator_expression:', random_list_generator_expression(quantity)) | |
if __name__ == '__main__': | |
cli.interface.cli() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment