我不知道这是否是最快的方法,但你可以尝试像这样做...
将Numpy数组存储到Redis中的方法如下 - 参见函数toRedis()
:
- 获取Numpy数组的形状并编码
- 将Numpy数组以字节形式附加到形状上
- 在提供的键下存储编码数组
检索Numpy数组的方法如下 - 参见函数fromRedis()
:
- 从Redis中检索与提供的键对应的编码字符串
- 从字符串中提取Numpy数组的形状
- 提取数据并重新填充Numpy数组,将其重新塑造为原始形状
import struct
import redis
import numpy as np
def toRedis(r,a,n):
"""Store given Numpy array 'a' in Redis under key 'n'"""
h, w = a.shape
shape = struct.pack('>II',h,w)
encoded = shape + a.tobytes()
r.set(n,encoded)
return
def fromRedis(r,n):
"""Retrieve Numpy array from Redis key 'n'"""
encoded = r.get(n)
h, w = struct.unpack('>II',encoded[:8])
a = np.frombuffer(encoded[8:]).reshape(h,w)
return a
a0 = np.arange(6400,dtype=np.uint16).reshape(80,80)
r = redis.Redis(host='localhost', port=6379, db=0)
toRedis(r,a0,'a0array')
a1 = fromRedis(r,'a0array')
np.testing.assert_array_equal(a0,a1)
你可以通过在形状信息中编码 Numpy 数组的 dtype 来增加更多的灵活性。我没有这样做是因为你可能已经知道所有数组都是特定类型的,那样代码只会变得更大更难读,而没有必要。
现代 iMac 上的粗略基准测试:
80x80 Numpy array of np.uint16 => 58 microseconds to write
200x200 Numpy array of np.uint16 => 88 microseconds to write
关键词: Python, Numpy, Redis, 数组, 序列化, 键, 自增, 唯一