генераторы_в_python

Генераторы в Python

Скрипт сравнивающий потребление памяти двумя функциями:

import memory_profiler as mem_profile # pip install memory_profiler
import random
import time
 
names = ['John', 'Jane', 'Steve', 'Rick', 'Tomas', 'Adam', 'Vadim']
majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']
 
print('Memory (Before): ' + str(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
 
def people_generator(num_people):
    for i in xrange(num_people):
        person = {
                    'id': i,
                    'name': random.choice(names),
                    'major': random.choice(majors)
                 }
        yield person
 
t1 = time.time()
people = people_list(1000000)
t2 = time.time()
 
print('Memory (After) : ' + str(mem_profile.memory_usage()) + 'MB')
print('Took ' + str(t2-t1) + ' Seconds')
# print(people)
 
# output
# Memory (Before): [25.7578125]MB
# Memory (After) : [296.1953125]MB
# Took 0.8566699028015137 Seconds
  • генераторы_в_python.txt
  • Последнее изменение: 2022/11/18 14:15
  • admin