在编写程序的过程中,有时候我们需要计算程序运行所需要的内存和运行时间,那么如何在Python中实现这些呢?
通过查阅了解,以下方法是当前较好的方式
程序示例:
#Python时间与内存比较评估函数
import memory_profiler as mem_profile
import random
import time
names = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']
# print('Memory (Before): {}Mb '.format(mem_profile.memory_usage_psutil()))
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 range(num_people):
person = {
'id': i,
'name': random.choice(names),
'major': random.choice(majors)
}
yield person
# t1 = time.clock()
# people = people_list(1000000)
# t2 = time.clock()
t1 =time.perf_counter()
# 使用此计时函数的原因 参考 https://blog.csdn.net/weixin_41974235/article/details/100740001
people = people_generator(1000000)
t2 = time.perf_counter()
# print 'Memory (After) : {}Mb'.format(mem_profile.memory_usage_psutil())
print('Memory (After) : ' + str(mem_profile.memory_usage()) + 'MB')
# print 'Took {} Seconds'.format(t2-t1)
print ('Took ' + str(t2-t1) + ' Seconds')
参考文章
[1] python - No module named mem_profile - Stack Overflow
[2] 关于python中time.perf_counter() 与 time.process_time()分析与疑问_pikachuabc的博客-CSDN博客