【问题标题】:implementing efficient fixed size FIFO in python在python中实现高效的固定大小FIFO
【发布时间】:2019-01-04 13:58:04
【问题描述】:

我需要在 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):

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) 还是有比上面介绍的更有效的解决方案?

顺便说一句,我的字符串的长度有一个最大上限,如果有帮助的话..

【问题讨论】:

    标签: python python-3.x numpy


    【解决方案1】:

    我会使用 NumPy。要指定最大字符串长度,请使用 dtype,如下所示:

    np.zeros(128, (str, 32)) # 128 strings of up to 32 characters
    

    【讨论】:

    • 谢谢@John。我的直觉也是使用 numpy。并感谢您告诉如何为字符串设置 maxsize。但我会等待一段时间以获得更详细的答案,为什么 numpy 选项比其他选项更好。
    • @R71:不客气。您现在要问的问题相当离题,因为它基本上是一项民意调查(“我应该使用这四个可行选项中的哪一个?”)。你也可以实现两个或三个,看看效果如何。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2012-02-17
    • 2016-01-25
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多