【问题标题】:diagnosing when I'm being limited by disk i/o当我受到磁盘 i/o 限制时进行诊断
【发布时间】:2016-02-07 21:48:55
【问题描述】:

我在 Linux 机器上运行 Python 2.7,到目前为止,我的脚本中最慢的部分是使用 ujson 库从磁盘(SSD)加载一个大型 json 文件。当我在这个加载过程中检查top 时,我的 cpu 使用率基本上是 100%,这让我相信我通过解析 json 而不是通过将字节从磁盘传输到内存而遇到了瓶颈。这是一个有效的假设,还是 ujson 在等待磁盘时会烧掉空循环或其他东西?我很想知道,因为我不确定将我的 cpu 的另一个核心用于另一个执行大量磁盘 i/o 的脚本是否会显着减慢第一个脚本的速度。

【问题讨论】:

    标签: python json linux performance ujson


    【解决方案1】:

    没有看到你的代码,我会假设你正在做这样的事情:

    with open('data.json') as datafile:
        data = json.loads(datafile.read())
    

    相反,您可以拆分读取文件和解析文件的步骤:

    with open('data.json') as datafile:
        raw_data = datafile.read()
        data = json.loads(raw_data)
    

    如果你添加一些计时调用,你可以确定每个步骤需要多长时间:

    # Timing decorator from https://www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods
    import time                                                
    
    def timeit(method):
    
        def timed(*args, **kw):
            ts = time.time()
            result = method(*args, **kw)
            te = time.time()
    
            print '%r (%r, %r) %2.2f sec' % \
                  (method.__name__, args, kw, te-ts)
            return result
    
        return timed
    
    with open('data.json') as datafile:
        @timeit
        raw_data = datafile.read()
        @timeit
        data = json.loads(raw_data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-20
      • 2019-12-07
      • 2012-10-10
      • 2019-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多