Created
February 28, 2022 06:13
-
-
Save musleh0001/0aae20428b9468d3589ef4fb3f7219eb to your computer and use it in GitHub Desktop.
Generator Memory Efficient
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
import memory_profiler as mem_profile | |
import random | |
import time | |
names = ["John", "Corey", "Adam", "Steve", "Rick", "Thomas"] | |
majors = ["Math", "Engineering", "CompSci", "Arts", "Business"] | |
print(f"Memory (Before): {mem_profile.memory_usage()}Mb") | |
def people_list(num_people): | |
result = [] | |
for i in range(num_people): | |
person = {"id": i, "name": random.choice(names), "major": random.choice(majors)} | |
result.append(person) | |
return result | |
# memory efficient | |
def people_generator(num_people): | |
for i in range(num_people): | |
person = {"id": i, "name": random.choice(names), "major": random.choice(majors)} | |
yield person | |
start = time.perf_counter() | |
people = people_generator(1000000) | |
end = time.perf_counter() | |
print(f"Memory (After): {mem_profile.memory_usage()}Mb") | |
print(f"Took {end - start:.4f} seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment