[英]Collect dict frames in a python object with appropriate and fast data structure
我正在使用一個API,該API每秒提供128個信號(和信號質量值)作為dict中的一個dict。 我想將它們收集到1(或更多)秒的窗口中。
我的本機方法是使用相同的dict結構並將值追加到列表中(例如: 在Python中將值追加到字典中 )。
參見示例:
# the API provides data like this
def getFrame(i):
return {"X":
{"value" : i,
"quality": i*2},
"AF3":
{"value" : i*3,
"quality": i*4}
}
# object to collect single frames
class WindowDto(object):
def __init__(self, windowSize, header):
self.header = header
self.windowSize = windowSize
self.data = {}
for key in self.header:
self.data[key] = {"value": [], "quality": []}
def addFrame(self, frame):
for key, val in frame.iteritems():
field = self.data[key]
field["value"].append(val["value"])
field["quality"].append(val["quality"])
# the keys of a frame are known
header = ["X", "AF3"]
# the max frame count is also known, but not used yet
maxFrameCount = 8
dto = WindowDto(maxFrameCount, header)
for i in range(8):
dto.addFrame(getFrame(i))
print(dto.data)
# {'X': {'quality': [0, 2, 4, 6, 8, 10, 12, 14], 'value': [0, 1, 2, 3, 4, 5, 6, 7]},
# 'AF3': {'quality': [0, 4, 8, 12, 16, 20, 24, 28], 'value': [0, 3, 6, 9, 12, 15, 18, 21]}}
我假設addFrame()
方法是一個潛在的瓶頸,因為我必須遍歷整個結構。 我正在尋找一種執行add
操作的更智能方法。 有什么建議怎么做?
我還可以自由更改值的存儲方式(例如在數組中?)以提高性能。 我知道標題值和窗口對象的最大大小。 這些值稍后將作為列表進行處理(例如sum(data["X"]["values"])
),但是訪問由WindowDto
包裹。
您是否進行了任何性能分析,也許您的服務器已經足夠好了!
import cProfile
cProfile.run('for i in range(128):dto.addFrame(getFrame(i))')
899 function calls in 0.001 seconds
cProfile.run('for i in range(128**2):dto.addFrame(getFrame(i))')
114691 function calls in 0.046 seconds
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.