我不知道它是否最快,但你可以试试这样的......
将 Numpy 数组存储到 Redis 如下所示 - 参见函数 toRedis():
- 获取 Numpy 数组的形状并编码
- 将 Numpy 数组作为字节附加到形状中
- 将编码数组存储在提供的密钥下
检索 Numpy 数组的过程如下 - 参见函数 fromRedis():
- 从 Redis 中检索与提供的键对应的编码字符串
- 从字符串中提取 Numpy 数组的形状
- 提取数据并重新填充 Numpy 数组,重塑为原始形状
#!/usr/bin/env python3
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()
# Store encoded data in Redis
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])
# Add slicing here, or else the array would differ from the original
a = np.frombuffer(encoded[8:]).reshape(h,w)
return a
# Create 80x80 numpy array to store
a0 = np.arange(6400,dtype=np.uint16).reshape(80,80)
# Redis connection
r = redis.Redis(host='localhost', port=6379, db=0)
# Store array a0 in Redis under name 'a0array'
toRedis(r,a0,'a0array')
# Retrieve from Redis
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、数组、序列化、序列化、键、增量、唯一