From 07daddb196cafe191176883c2f080b3d224f5a6f Mon Sep 17 00:00:00 2001 From: guanjihuan Date: Sat, 29 Mar 2025 08:47:45 +0800 Subject: [PATCH] Create matrix_memory.py --- 2025.03.29_matrix_memory/matrix_memory.py | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 2025.03.29_matrix_memory/matrix_memory.py diff --git a/2025.03.29_matrix_memory/matrix_memory.py b/2025.03.29_matrix_memory/matrix_memory.py new file mode 100644 index 0000000..c105739 --- /dev/null +++ b/2025.03.29_matrix_memory/matrix_memory.py @@ -0,0 +1,41 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/45873 +""" + +import numpy as np +import sys + +n_array = np.concatenate((np.arange(1, 10, 1), + np.arange(10, 100, 10), + np.arange(100, 1000, 100), + np.arange(1000, 10000, 1000), + np.arange(10000, 100000, 10000), + np.arange(100000, 1000000, 100000))) + +for n in n_array: + matrix = np.zeros((n, n)) # 双精度浮点数 float64 一个数据占用 8B + # matrix = np.zeros((n, n), dtype=complex) # 双精度复数 complex128 一个数据占用 16B + # matrix = np.zeros((n, n), dtype=np.float32) # 单精度浮点数 float32 一个数据占用 4B + # matrix = np.zeros((n, n), dtype=int) # 整数 int32 一个数据占用 4B + if n==1: + print(type(matrix[0, 0]), '\n') + size0 = matrix.nbytes # 矩阵数据内存占用 + size = sys.getsizeof(matrix) # 矩阵总的内存占用 + print(f'矩阵 N={n}') + if size<1024: + print(f'数据内存占用: {size0:.2f} B') + print(f'总的内存占用: {size:.2f} B') + elif 1024