本文来探索一下python中提供的各种数据保存格式的性能如何。主要以一个 ndarray 格式的数据进行处理分析。包括下面几种方式:
- .bin格式, np.tofile() 和 np.fromfile()
- .npy格式,np.save() 和 np.load()
- .txt 或者 .csv格式,np.savetxt() 和 np.loadtxt()
- .h5 格式,h5py.File(,’r’ 或者 ‘w’)
- .pkl 格式, pickle.dump()和pickle.load()
import numpy as np
from __future__ import print_function
import time
a = np.random.randint(0, 100, size=(10000, 5000))
print(a.dtype, a.shape)
print(a[:2])
int64 (10000, 5000)
[[90 96 38 ..., 67 40 79]
[40 12 71 ..., 64 76 15]]
1. np.tofile() 和 np.fromfile()
%time a.tofile('data/a.bin')
%time b = np.fromfile('data/a.bin', dtype=np.int64)
print(b.shape)
print(b[:2])
CPU times: user 4 ms, sys: 392 ms, total: 396 ms
Wall time: 2.06 s
CPU times: user 4 ms, sys: 156 ms, total: 160 ms
Wall time: 160 ms
(50000000,)
[90 96]
读入数据的时候要正确设置 dtype 参数
读入的数据是一维的,还需要经过 reshape 处理。
2. np.save()和np.load()
%time np.save('data/a.npy', a)
%time b = np.load('data/a.npy')
print(b.shape)
pr