我需要在 python 或 numpy 中有效地实现固定大小的 FIFO。我可能有不同的此类 FIFO,一些用于整数,一些用于字符串等。在这个 FIFO 中,我需要通过索引访问每个元素。
关注效率是因为这些 FIFO 将被用在一个预计连续运行几天的程序的核心,并且预计会有大量数据通过它们。因此,算法不仅需要具有时间效率,还必须具有内存效率。
现在在 C 或 Java 等其他语言中,我会使用循环缓冲区和字符串指针(用于字符串 FIFO)有效地实现这一点。这是 python/numpy 中的有效方法,还是有更好的解决方案?
具体来说,以下哪种解决方案最有效:
(1) dequeue with maxlen value set:(垃圾回收对dequeue的效率有什么影响?)
import collections
l = collections.deque(maxlen=3)
l.append('apple'); l.append('banana'); l.append('carrot'); l.append('kiwi')
print(l, len(l), l[0], l[2])
> deque(['banana', 'carrot', 'kiwi'], maxlen=3) 3 banana kiwi
(2) 列出子类解决方案(取自Python, forcing a list to a fixed size):
class L(list):
def append(self, item):
list.append(self, item)
if len(self) > 3: self[:1]=[]
l2.append('apple'); l2.append('banana'); l2.append('carrot'); l2.append('kiwi')
print(l2, len(l2), l2[2], l2[0])
> ['banana', 'carrot', 'kiwi'] 3 kiwi banana
(3) 一个普通的 numpy 数组。但这限制了字符串的大小,那么如何为此指定最大字符串大小呢?
a = np.array(['apples', 'foobar', 'cowboy'])
a[2] = 'bananadgege'
print(a)
> ['apples' 'foobar' 'banana']
# now add logic for manipulating circular buffer indices
(4) 以上的对象版本,但是 python numpy array of arbitrary length strings说使用对象会破坏 numpy 的好处
a = np.array(['apples', 'foobar', 'cowboy'], dtype=object)
a[2] = 'bananadgege'
print(a)
> ['apples' 'foobar' 'bananadgege']
# now add logic for manipulating circular buffer indices
(5) 还是有比上面介绍的更有效的解决方案?
顺便说一句,我的字符串的长度有一个最大上限,如果这有帮助的话......
最佳答案
我会使用 NumPy。要指定最大字符串长度,请使用 dtype
,如下所示:
np.zeros(128, (str, 32)) # 128 strings of up to 32 characters
关于python - 在 python 中实现高效的固定大小 FIFO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51558015/