模块未命名为mem_profile。

7

我正在使用这个程序来测量两个函数所使用的时间和内存,并比较哪个更适合处理大量数据。我的理解是,要测量内存使用情况,我们需要使用 mem_profile 模块,但在执行 pip install mem_profile 时出现了错误 No module named mem_profile

import mem_profile
import random
import time

names = ['Kiran','King','John','Corey']
majors = ['Math','Comps','Science']

print 'Memory (Before): {}Mb'.format(mem_profile.memory_usage_resource())

def people_list(num_people):
    results = []
    for i in num_people:
        person = {
                    'id':i,
                    'name': random.choice(names),
                    'major':random.choice(majors)
                  }
        results.append(person)
    return results

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.clock()
people = people_list(10000000)
t2 = time.clock()


# t1 = time.clock()
# people = people_generator(10000000)
# t2 = time.clock()

print 'Memory (After): {}Mb'.format(mem_profile.memory_usage_resource())
print 'Took {} Seconds'.format(t2-t1)

这个错误是什么原因引起的?有没有其他替代的软件包可供使用?

1
我刚刚看了这个视频 https://www.youtube.com/watch?v=bD05uGo_sVI,我在这里看到完全相同的代码。 - Pyzard
10个回答

20

1)首先导入模块

pip install memory_profiler

2)像这样将其包含在您的代码中

import memory_profiler as mem_profile

3)更改代码

mem_profile.memory_usage_psutil()更改为memory_usage()

4)将你的打印语句转换成这样

print('Memory (Before): ' + str(mem_profile.memory_usage()) + 'MB' )
print('Memory (After) : ' + str(mem_profile.memory_usage()) + 'MB')
print ('Took ' + str(t2-t1) + ' Seconds')

5) 你将得到类似以下代码:

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.clock()
people = people_generator(1000000)
t2 = time.clock()

# 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')

现在它运行得很好,我正在使用Python 3.6,而且没有任何错误。


嘿,生成器的分析有误导性,因为在people_generator中没有任何东西被“生成”。 - user3785966

13

我看了同样的教程并遇到了同样的问题。但是在进一步的研究中,我发现教程的作者使用了一个叫做memory_profiler的软件包,他将其主文件更改为mem_profile,然后在代码教程中导入。

只需执行pip install memory_profiler。将该文件复制并重命名为mem_profile.py放在您的工作目录中,就可以解决这个问题了。如果您使用的是Windows,请确保还安装了相关的psutil软件包。

希望能对某人有所帮助。


7

使用此方法计算时间:

import time

time_start = time.time()
#run your code
time_elapsed = (time.time() - time_start)

根据Python文档所述:

time.time() → float 将时间作为浮点数返回,单位为自纪元以来的秒数。 纪元日期及闰秒处理因平台而异。在Windows和大多数Unix系统中, 纪元是1970年1月1日00:00:00(UTC),并且闰秒不计入自纪元以来的秒数。 这通常被称为Unix时间。要查找给定平台上的纪元,请查看gmtime(0)。

请注意,尽管始终将时间作为浮点数返回,但并非所有系统都提供比1秒更高的精度。 虽然此函数通常返回非递减值,但如果在两个调用之间系统时钟已被设置回,则它可能会返回一个较低的值。

通过将其传递给gmtime()函数可以将由time() 返回的数字转换为UTC中的常见时间格式(即年月日,小时等), 或者通过将其传递给localtime()函数将其转换为本地时间。在这两种情况下,都会返回struct_time对象, 从中可以将日历日期的组件作为属性访问。

参考资料: https://docs.python.org/3/library/time.html#time.time


计算内存使用量时请使用此功能:

import resource

resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

参考资料: http://docs.python.org/library/resource.html

如果您正在使用Python 3.x,请使用以下方法:

参考资料: https://docs.python.org/3/library/timeit.html


2
不要使用time.clock(),它会误导你并且已经被弃用。你引用的参考文献已经过时,在较新版本的Python3文档中已经更新。 - Corey Goldberg
你是在谈论这个吗?@CoreyGoldberg - Devansh
我目前在Python方面没有太多经验,我正在使用Python 2.7进行工作,因此我基于这个找到了解决方案。当使用Python 3.x时,我同意@CoreyGoldberg的观点。 - Devansh
2
是的。time.clock() 在Windows和其他平台上的行为也不同。我建议删除这个答案。 - Corey Goldberg
1
无论你使用哪个版本的Python,这篇答案都提供了错误的计时代码建议。 - Corey Goldberg
你可以使用 time.time(),它返回自 Epoch 以来经过的精确秒数(一个 float)。因此, import time; t1 = time.time(); t2 = time.time(); print(t2) 将输出自 t1 创建以来经过的时间。 - Pyzard

5
Adebayo Ibro 的回答中,添加以下内容:
  • 在终端中运行 $ pip install memory_profiler
  • 在您的脚本中,将 import mem_profile 替换为 import memory_profiler as mem_profile
  • 在您的脚本中,将全部mem_profile.memory_usage_resource() 替换为 mem_profile.memory_usage()
希望这能帮到您!

3

那个模块是手写的(不在Python包中)。 我从Corey Schafer在他的YouTube视频评论中得到了这个。 只需将此代码保存为模块的名称:

from pympler import summary, muppy
import psutil
import resource
import os
import sys

def memory_usage_psutil():
    # return the memory usage in MB
    process = psutil.Process(os.getpid())
    mem = process.get_memory_info()[0] / float(2 ** 20)
    return mem

def memory_usage_resource():
    rusage_denom = 1024.
    if sys.platform == 'darwin':
        # ... it seems that in OSX the output is different units ...
        rusage_denom = rusage_denom * rusage_denom
    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / rusage_denom
    return mem

2

我遇到了相同的问题。 我通过安装memory_profiler$ pip install -U memory_profiler)解决了它,并按如下方式修改了程序:

import memory_profiler
...
print('Memory (Before): {}Mb'.format(memory_profiler.memory_usage()))

1
自从time.clock()被移除,以及print()的进化,Python 3.8进行了一些更新。
感谢大家参与讨论,特别感谢Corey Schafer出色的视频。
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

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.process_time()
# people = people_list(1000000)
# t2 = time.process_time()

t1 = time.process_time()
people = people_generator(1000000)
t2 = time.process_time()


print(f'Memory (After): {mem_profile.memory_usage()}Mb')

print(f'Took {t2-t1} Seconds')

1

我经历了相同的教程 这个库的名称是memory_profiler 为了安装,你可以使用以下命令

pip install -U memory_profiler

导入

import memory_profiler

注意:该库没有memory_usage_resource函数,但您可以使用具有相同功能的memory_usage。不要使用clock()函数,而是使用time()函数。
import memory_profiler
import random
import time

names=['John', 'Jane', 'Adam','Steve', 'Rick','George','Paul','Bill','Bob']
majors=['Math','Engineering','ComSic','Arts','Stuck Broker']

print ('Memory (Before): {} MB'.format(memory_profiler.memory_usage()))
#using list
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


#using generators
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.time()
# people_list(1000000)
# t2=time.time()

t1=time.time()
people_generator(1000000)
t2=time.time()

print('Memory (After): {} MB'.format(memory_profiler.memory_usage()))
print ('Took {} seconds'.format(t2-t1))

0

使用sys更加简单

    import sys
    ...
    print ('Memory (Before): {0}Mb'.format(sys.getsizeof([])))

-1
在执行 pip install mem_profile 命令时,出现了 No module named mem_profile 的错误提示。
默认情况下,pip 会从 PyPI 下载软件包。但是,PyPI 上并没有名为“mem_profile”的软件包,因此你会收到错误提示。

如果要计时代码块,timeit 模块是您想要使用的工具: https://docs.python.org/library/timeit.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接