高效的循环缓冲区? [英] efficient circular buffer?

查看:63
本文介绍了高效的循环缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 python 中创建一个高效的循环缓冲区(目的是取整数值的平均值)缓冲).

这是使用列表收集值的有效方法吗?

def add_to_buffer( self, num ):self.mylist.pop( 0 )self.mylist.append( num )

什么会更有效(以及为什么)?

解决方案

我会使用 collections.deque 带有 maxlen arg

<预><代码>>>>进口藏品>>>d = collections.deque(maxlen=10)>>>d双端队列([], maxlen=10)>>>对于 xrange(20) 中的 i:... d.append(i)...>>>d双端队列([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], maxlen=10)

deque 的文档中有一个 recipe 与您想要的类似.我断言它是最有效的完全基于这样一个事实,即它是由非常熟练的团队用 C 实现的,他们习惯于编写一流的代码.

I want to create an efficient circular buffer in python (with the goal of taking averages of the integer values in the buffer).

Is this an efficient way to use a list to collect values?

def add_to_buffer( self, num ):
    self.mylist.pop( 0 )
    self.mylist.append( num )

What would be more efficient (and why)?

解决方案

I would use collections.deque with a maxlen arg

>>> import collections
>>> d = collections.deque(maxlen=10)
>>> d
deque([], maxlen=10)
>>> for i in xrange(20):
...     d.append(i)
... 
>>> d
deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], maxlen=10)

There is a recipe in the docs for deque that is similar to what you want. My assertion that it's the most efficient rests entirely on the fact that it's implemented in C by an incredibly skilled crew that is in the habit of cranking out top notch code.

这篇关于高效的循环缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆