I want to have a table of 10 largest objects in memory, with size.
Equivalent function in R: Tricks to manage the available memory in an R session
lsos()
# Type Size(MB) Rows Columns
#d2 data.table 157.8364 281444 74
#d data.table 62.2658 816078 11
Edit: @ 9.0 Here is my attempt.
I have to use globals()
, using gc.get_objects()
makes my computer very slow. I am not sure globals()
gives me what I want.
How to get the list of all initialized objects and function definitions alive in python?
def lsos(n=10):
import pandas as pd
import sys
all_obj =globals()
object_name = list(all_obj).copy()
object_size = [sys.getsizeof(all_obj[x]) for x in object_name]
d = pd.DataFrame(dict(name = object_name, size = object_size))
d.sort_values(['size'], ascending=[0],inplace=True)
return(d.head(n))
v = list(range(1000))
v2 = list(range(10000))
v3 = list(range(100000))
v4 = v3
lsos()
# name size
# 0 v4 900112
# 22 v3 900112
# 1 v2 90112
# 17 v 9112
# 6 _i 395
# 14 _i1 395
# 19 _oh 288
# 24 Out 288
# 5 _i2 137
# 3 lsos 136
When I put the above function in say abc.py
and run
import abc
abc.lsos()
# name size
# 8 __builtins__ 6240
# 0 lsos 136
# 6 __file__ 123
# 2 __cached__ 97
# 1 __loader__ 56
# 4 __spec__ 56
# 5 __name__ 54
# 3 __package__ 49
# 7 __doc__ 16
None of the large v
appears.
Edit 2:
Because there's problem of accessing globals()
in a module, I just pass globals()
to the module, here is what I am using now:
#abc.py
def lsos(all_obj = globals(),n=10):
import sys
object_name = list(all_obj)
object_size = [ round(sys.getsizeof(all_obj[x])/1024.0/1024.0,4) for x in object_name]
object_id = [id(all_obj[x]) for x in object_name]
d = [(a,b,c) for a,b,c in zip(object_name, object_size, object_id)]
d.sort(key = lambda x:(x[1],x[2]), reverse=True)
dprint = d[0:min(len(d), n)]
#print formating
name_width_max = max([len(x[0]) for x in dprint])
print(("{:<" + str(name_width_max +2) + "}{:11}{}").format("name","size_Mb","id"))
fmt = '{{:<{}}}'.format(name_width_max+2) +" "+ "{: 5.4f}" +" "+ "{:d}"
for line in dprint:
print( fmt.format(*line))
return
Then it can be called by
import abc
abc.lsos(globals())