【问题标题】:Python performance profiling (file close)Python 性能分析(文件关闭)
【发布时间】:2012-11-26 16:36:31
【问题描述】:

首先感谢您的关注。我的问题是如何减少我的代码的执行时间。

这里是相关代码。下面的代码在 main 的迭代中被调用。

def call_prism(prism_input_file,random_length):
   prism_output_file = "path.txt"
   cmd = "prism %s -simpath %d %s" % (prism_input_file,random_length,prism_output_file)
   p = os.popen(cmd)
   p.close()
   return prism_output_file


def main(prism_input_file, number_of_strings):
...
  for n in range(number_of_strings):
        prism_output_file = call_prism(prism_input_file,z[n])
        ...

  return

当我分析我的代码时,我使用了来自“配置文件统计浏览器”的统计信息。 “文件关闭”系统命令花费的时间最长(14.546 秒)。 call_prism 例程被调用 10 次。但是 number_of_strings 通常是数千,所以,我的程序需要很多时间才能完成。

如果您需要更多信息,请告诉我。顺便说一句,我也尝试过使用子流程。谢谢。

【问题讨论】:

  • 您应该使用 subprocess ,因为它可以替代所有其他调用进程的方式。但如果您必须使用系统进程,我认为您无能为力。它们很贵。
  • 如果你调用一些琐碎的命令而不是 prism,比如echop.close() 还会占用这么多时间吗?棱镜过程很可能在终止时需要一些长时间的清理操作。顺便说一句,如果 prism 调用不相互依赖,您可能会通过在并行线程中运行多个进程(例如在每个内核的线程上)来严重缩短执行时间。

标签: python performance file profiling


【解决方案1】:

感谢您对我的问题的反馈。根据其他人提供的 cmets,我做了一个并行版本的代码,代码的性能确实得到了提高。这是并行版本的sn-p。欢迎您的反馈,如果有的话。

def call_prism(prism_input_file,random_length):
    ...   
    cmd = "prism %s -simpath %d stdout" % (prism_input_file,random_length)
    args = shlex.split(cmd)
    p = subprocess.Popen(args,stdout=subprocess.PIPE)
    p.poll()
    prism_output_lines = p.stdout.readlines()
    ...
    return ...

def call_prism_star(prism_input_file_random_length):
   return call_prism(*prism_input_file_random_length)

def main(prism_input_file, number_of_strings,number_of_threads):
   pool = Pool(processes=number_of_threads)
   for n in range(0,number_of_strings,number_of_threads):
   ...
      for i in range(number_of_threads):
          a_args.append(...)
      output = pool.map(call_prism_star,itertools.izip(itertools.repeat(prism_input_file),a_args))
   ...
    return

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    相关资源
    最近更新 更多