Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么这个字典更新代码很慢?我如何改进它';什么是效率?_Python_Performance_Python 2.7_Dictionary - Fatal编程技术网

Python 为什么这个字典更新代码很慢?我如何改进它';什么是效率?

Python 为什么这个字典更新代码很慢?我如何改进它';什么是效率?,python,performance,python-2.7,dictionary,Python,Performance,Python 2.7,Dictionary,我试图减少python应用程序所消耗的处理器时间,在对其进行分析之后,我发现一小段代码所消耗的处理器时间超过了它应该消耗的时间: class Stats(DumpableObject): members_offsets = [ ('blkio_delay_total', 40), ('swapin_delay_total', 56), ('read_bytes', 248), ('write_bytes', 256),

我试图减少python应用程序所消耗的处理器时间,在对其进行分析之后,我发现一小段代码所消耗的处理器时间超过了它应该消耗的时间:

class Stats(DumpableObject):
    members_offsets = [
        ('blkio_delay_total', 40),
        ('swapin_delay_total', 56),
        ('read_bytes', 248),
        ('write_bytes', 256),
        ('cancelled_write_bytes', 264)
    ]

[...other code here...]

    def accumulate(self, other_stats, destination, coeff=1):
        """Update destination from operator(self, other_stats)"""
        dd = destination.__dict__
        sd = self.__dict__
        od = other_stats.__dict__
        for member, offset in Stats.members_offsets:
            dd[member] = sd[member] + coeff * od[member]
为什么这么贵?如何提高此代码的效率

背景: 我最喜欢的Linux工具之一,使用的处理器时间远远超过了我认为适合监视工具的时间——很快就占用了几分钟的处理器时间;使用内置的--profile选项,运行20秒的函数调用总数接近400万次。我在其他系统上观察到了类似的行为,包括重新启动和多个内核。pycallgraph突出显示了
累积
,作为少数耗时函数之一

在研究了整整一周的代码之后,我认为字典是这里数据结构的最佳选择,因为大量要更新的线程将需要很多查找,但我不明白为什么这段代码很昂贵。广泛的搜索并没有带来启发。我对
诅咒
套接字
结构
库的理解不够透彻,无法提出一个独立的问题。我并不要求代码像i7z中的纯C那样轻量级

我会发布图片和其他数据,但我没有声誉

iotop git存储库:(问题代码位于data.py中,第73行开始)

该系统在英特尔E6420上运行Ubuntu 13.04,内存为2GB。内核3.8.0-35-generic


(我真希望纪尧姆·查扎伦(Guillaume Chazarain)能写更多的文档!)

我觉得这段代码相当精简。您根本没有使用
偏移量
,因此对于
Stats.member\u offset
(您可以避免元组解包的成本)来说,
dict
可能是一个更好的选择。但这应该是一个相当小的优化。老实说,你的问题到处都是--
诅咒
套接字
结构
?这些和手头的问题有什么关系?你怎么知道这比它应该的慢?你确定它很贵,还是只是经常被呼叫?同意@BrenBarn。对我来说真的没那么贵。