You can prevent memory leaks by creating and terminating the drawing process separately as shown below.
from multiprocessing import Pool
import matplotlib.pyplot as plt
import numpy as np
#Method for plotting
# plt.clf()・ Plt.close()The memory is automatically released when the process ends without doing this.
def plot(args):
x, y = args
plt.plot(x, y)
#Value to plot
x = np.arange(1e7)
y = np.arange(1e7)
#Create a process for plotting and perform drawing processing in it
p = Pool(1)
p.map(plot, [[x,y]])
p.close()
You can check if the memory is actually released with the following code.
from multiprocessing import Pool
import matplotlib.pyplot as plt
import numpy as np
#Method for plotting
# plt.clf()・ Plt.close()Memory is automatically released when the process ends without doing this.
def plot(args):
x, y = args
plt.plot(x, y)
#You may do the following for verification
plt.tight_layout()
plt.savefig('aa.jpeg')
#Plot 10 times to see if memory usage changes
for i in range(10):
#Value to plot
x = np.arange(1e7)
y = np.arange(1e7)
#Create a process for plotting and perform drawing processing in it
p = Pool(1)
p.map(plot, [[x,y]])
p.close()
#Show memory usage
import psutil
mem = psutil.virtual_memory().free / 1e9
print(i, f'memory used: {mem} [GB]')
By the way, a memory leak occurs in the following cases, for example. (Reference: Memory may not be released just by plt.close ()-Qiita)
--If you only do plt.close ()
--If you are doing plt.clf ()
→ plt.close ()
, but you are doing plt.tight_layout ()
or plt.savefig ()
Recommended Posts