关于python程序使用pyinstaller打包exe, 执行过程中内存不断增长问题
- 我使用的python版本为3.7.9 打包使用 pyinstaller
- 最开始 使用的是 objgraph 模块,会显示变量的类型总数的增长数量的显示, 但是只显示变量 类型,不显示变量属性,不容易直接观看
# !/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
# 复制代码
import objgraph as objgraph
objgraph.show_growth()
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "root", "root", '', 3306)
print(type(db))
# 使用cursor()方法获取操作游标
cursor = db.cursor()
print(type(cursor))
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据库。
data = cursor.fetchone()
print(type(data))
print("Database version : %s " % data)
# 关闭数据库连接
db.close()
# del db
# del cursor
# del data
import objgraph as objgraph
objgraph.show_growth()
结果显示如下, 效果不是很明显
function 7600 +7600
dict 3999 +3999
tuple 3219 +3219
wrapper_descriptor 2012 +2012
weakref 1814 +1814
list 1746 +1746
method_descriptor 1474 +1474
builtin_function_or_method 1394 +1394
getset_descriptor 1353 +1353
type 1028 +1028
<class 'MySQLdb.connections.Connection'>
<class 'MySQLdb.cursors.Cursor'>
<class 'tuple'>
Database version : 8.0.25
function 7673 +73
method_descriptor 1543 +69
dict 4054 +55
set 535 +37
tuple 3255 +36
FuncCodeInfo 281 +33
wrapper_descriptor 2041 +29
weakref 1839 +25
type 1050 +22
getset_descriptor 1370 +17
- 我找到了memory_profiler这个第三方库,它可以帮助我们分析记录Python脚本中,执行到每一行时,内存的消耗及波动变化情况。
memory_profiler的使用方法超级简单,使用pip install memory_profiler完成安装后,只需要从memory_profiler导入profile并作为要分析的目标函数的装饰器即可
#!/usr/bin/python
# -*- coding:utf-8 -*-
from matplotlib import pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from memory_profiler import profile
@profile
def iris_test():
scores = []
ks = []
iris = datasets.load_iris()
feature = iris['data']
target = iris['target']
# 拆分出训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(feature, target, test_size=0.2, random_state=2020)
print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)
# 5.实例化模型对象
# n_neighbors == k-在knn中k的取值不同会直接导致分类结果的不同,n_neighbors就是K值。
# ·模型的超参数:如果模型参数有不同的取值且不同的取值会模型的分类或者预测会产生直系的影响。
knn = KNeighborsClassifier(n_neighbors=5)
print(knn)
# 6.使用训练集数据训练模型
# X:训练集的特征数据、特征数据的维度必须是二维。
# y:训练集的标签数据
knn = knn.fit(x_train, y_train)
# 7.测试模型:使用测试数据
# predict表示使用训练好的模型实现分类或者预测
y_pred = knn.predict(x_test)
# 模型基于测试数据返回的分类结果
y_true = y_test
# 测试集真实的分类结果
print('模型的分类结果:', y_pred)
print('