我需要在python或numpy中高效地实现固定大小的FIFO。我可能有不同的FIFO,一些用于整数,一些用于字符串,等等。在这个FIFO中,我需要通过它的索引访问每个元素。在
对效率的关注是因为这些fifo将被用于一个预计将连续运行数天的程序的核心,并且大量的数据预计将通过它们。因此,算法不仅需要时间效率,而且还必须具有内存效率。在
现在在其他语言如C或Java中,我可以使用循环缓冲区和字符串指针(对于字符串fifo)有效地实现这一点。在python/numpy中,这是一种高效的方法,还是有更好的解决方案?在
具体来说,以下哪种解决方案最有效:
(1)设置maxlen值的出列:(垃圾回收对出列效率有什么影响?)在
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):
^{pr2}$(3)一个普通的纽比阵列。但是这限制了字符串的大小,那么如何为它指定最大字符串大小呢?在
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)或者是否有比上述方法更有效的解决方案?在
顺便说一句,我的字符串的长度有一个最大上限,如果这有帮助的话。。在
我会用纽比。要指定最大字符串长度,请使用
dtype
,如下所示:相关问题 更多 >
编程相关推荐