[英]Figure out how much memory an operation takes
How would I figure out how much memory an operation takes? 我如何确定一个操作需要多少内存? For example:
例如:
memory_start = memory()
reader = csv.reader(file)
memory_end = memory()
memory_of_reader = math.abs(memory_end - memory_start)
If you want to get the size of an object you can use sys.getsizeof
that return the size of an object in bytes. 如果要获取对象的大小,则可以使用
sys.getsizeof
,它以字节为单位返回对象的大小。
sys.getsizeof(object[, default])
sys.getsizeof(object [,默认])
Return the size of an object in bytes.
返回对象的大小(以字节为单位)。 The object can be any type of object.
该对象可以是任何类型的对象。 All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.
所有内置对象都将返回正确的结果,但是对于第三方扩展,这不一定成立,因为它是特定于实现的。
If given, default will be returned if the object does not provide means to retrieve the size.
如果给定,则如果对象不提供检索大小的方法,则将返回默认值。 Otherwise a
TypeError
will be raised.否则会引发
TypeError
。
getsizeof()
calls the object's__sizeof__
method and adds an additional garbage collector overhead if the object is managed by the garbage collector.如果对象由垃圾收集器管理,则
getsizeof()
调用对象的__sizeof__
方法并添加额外的垃圾收集器开销。
example : 例如:
>>> import sys
>>> a=2
>>> sys.getsizeof(a)
24
>>> a='this is a test'
>>> sys.getsizeof(a)
51
And for more advanced tasks you can use memory_profiler that is a module for monitoring memory usage of a python program 对于更高级的任务,您可以使用memory_profiler这个模块,用于监视python程序的内存使用情况
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.