Python 动态写入大文件避免 100% CPU 使用

Python Write dynamically huge files avoiding 100% CPU Usage

我正在 this great stuff 的帮助下解析一个巨大的 CSV 大约 2 GB 的文件。现在必须为新文件中的每一列生成动态文件,其中列名作为文件名。所以我写了这段代码来写动态文件:

def write_CSV_dynamically(self, header, reader):
  """
  :header - CSVs first row in string format
  :reader - CSVs all other rows in list format  
  """

  try:
    headerlist =header.split(',') #-- string headers 
    zipof = lambda x, y: zip(x.split(','), y.split(','))
    filename = "{}.csv".format(self.dtstamp)
    filename = "{}_"+filename
    filesdct = {filename.format(k.strip()):open(filename.format(k.strip()), 'a')\
    for k in headerlist}
    for row in reader:
      for key, data in zipof(header, row):
        filesdct[filename.format(key.strip())].write( str(data) +"\n" )
    for _, v in filesdct.iteritems():
      v.close()
  except Exception, e:
    print e

现在使用 100% CPU 编写这些大文件大约需要 50 秒。因为我的服务器上还有其他繁重的东西 运行。我想阻止我的程序只使用 10% 到 20% 的 CPU 并写入这些文件。不管是否需要 10-15 分钟。 我如何优化我的代码,使其限制 10-20% CPU 的使用。

有多种方法可以实现:

  • Nice 过程 - 简单明了。

  • cpulimit - 只需将您的脚本和 cpu 用法作为参数传递:

    cpulimit -P /path/to/your/script -l 20

  • Python 的 resource 包从脚本设置限制。请记住,它适用于绝对 CPU 时间。