我不知道它是否最快,但是您可以尝试类似的方法…
将一个Numpy数组存储到Redis就像这样-see function
toRedis():
- 获得Numpy数组的形状并进行编码
- 将Numpy数组作为字节附加到形状
- 将编码的数组存储在提供的密钥下
检索一个Numpy数组是这样的-see function
fromRedis():
- 从Redis检索与提供的密钥相对应的编码字符串
- 从字符串中提取Numpy数组的形状
- 提取数据并重新填充Numpy数组,重塑为原始形状
#!/usr/bin/env python3import structimport redisimport numpy as npdef toRedis(r,a,n): """Store given Numpy array 'a' in Redis under key 'n'""" h, w = a.shape shape = struct.pack('>II',h,w) enpred = shape + a.tobytes() # Store enpred data in Redis r.set(n,enpred) returndef fromRedis(r,n): """Retrieve Numpy array from Redis key 'n'""" enpred = r.get(n) h, w = struct.unpack('>II',enpred[:8]) a = np.frombuffer(enpred, dtype=np.uint16, offset=8).reshape(h,w) return a# Create 80x80 numpy array to storea0 = np.arange(6400,dtype=np.uint16).reshape(80,80)# Redis connectionr = redis.Redis(host='localhost', port=6379, db=0)# Store array a0 in Redis under name 'a0array'toRedis(r,a0,'a0array')# Retrieve from Redisa1 = fromRedis(r,'a0array')np.testing.assert_array_equal(a0,a1)您可以通过
dtype对Numpy数组的以及形状进行编码来增加灵活性。我之所以没有这样做,是因为您可能已经知道所有数组都属于一种特定类型,然后代码会变得更大且更难于无故读取。
在现代iMac上的大致基准 :
80x80 Numpy array of np.uint16 => 58 microseconds to write200x200 Numpy array of np.uint16 => 88 microseconds to write
关键字 :Python,Numpy,Redis,数组,序列化,序列化,键,incr,唯一



