Python如何查看变量占用空间大小

在c语言中提供了sizeof可以用来查看一个变量占用的空间大小,在python中可以使用sys模块下的getsizeof方法来判断变量占用的空间大小。其文档解释如下:[mw_shl_code=python,true]sys.getsizeof(object[, default]):[/mw_shl_code]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.The default argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a TypeError.getsizeof calls the object’s sizeof method and adds an additional garbage collector overhead if the object is managed by the garbage collector.使用示例:[mw_shl_code=python,true]import sysv = 1print sys.getsizeof(v)s = 'abc'print sys.getsizeof(s)[/mw_shl_code]

青春有我
浏览 2884回答 1
1回答

翻翻过去那场雪

sys.getsizeof(object[, default])下面是我摘录的,希望对你有用。以字节(byte)为单位返回对象大小。 这个对象可以是任何类型的对象。 所以内置对象都能返回正确的结果 但不保证对第三方扩展有效,因为和具体实现相关。getsizeof() 调用对象的 __sizeof__ 方法, 如果对象由垃圾收集器管理, 则会加上额外的垃圾收集器开销。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python