我不知道它是否最快,但你可以尝试这样的事情......
将 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)
您可以通过编码来增加更多的灵活性dtype
Numpy 数组以及形状。我没有这样做,因为您可能已经知道所有数组都是一种特定类型,然后代码会无缘无故地变得更大并且更难以阅读。
现代 iMac 上的粗略基准测试:
80x80 Numpy array of np.uint16 => 58 microseconds to write
200x200 Numpy array of np.uint16 => 88 microseconds to write
Keywords:Python、Numpy、Redis、数组、序列化、序列化、键、增量、唯一