【问题标题】:How to aquire in Python the execution time of a gnuplot script?如何在 Python 中获取 gnuplot 脚本的执行时间?
【发布时间】:2015-03-12 10:10:34
【问题描述】:

我对 Python 很陌生,现在我正在尝试使用它。 我想通过以下方式导入 Gnuplot 脚本的执行时间:

 import os
 run_time = os.system("time gnuplot sript.gnuplot")
 print "run time:",run_time

我得到的是这样的:

run time: 256

如果没有任何东西可以运行,它是零,如果它正在做某事,它是 256。 run_time 的类型是 int 我试图得到这种字符串

0.65user 0.06system 0:00.72elapsed

目前我不知道自己做错了什么,但我会继续调查。

我的问题是是否有另一种方法来衡量这个执行时间,或者我是否可以通过某种方式更正我的代码。

所有这一切的重点是我想将这段时间用作 python 脚本的暂停,以便让 Gnuplot 有足够的时间来适应我的数据。如果我在 python 中导入 gnuplot 库,我不知道我需要多少时间来拟合我想要的每个图,所以我不想停止这个过程并得到一个不好的拟合。(例如,我想如果我使用暂停是一个坏主意,因为对于我模拟然后尝试拟合的每组数据点,直到拟合完成所需的时间对于每个图都不同)。我希望我尽可能清楚地说明问题!

提前致谢!

【问题讨论】:

  • 为什么需要暂停 Python?调用 os.system 将等到它完成。

标签: python time gnuplot


【解决方案1】:

os.system 函数为您提供程序的返回码,而不是它发送到其输出的字符串。

使用 subprocess 模块代替启动 gnuplot:

import subprocess
run_time_str = subprocess.check_output(['time', 'gnuplot', 'sript.gnuplot'])
print 'run time:', run_time_str

您还可以使用timeit 模块直接在 Python 中测量时间:

import subprocess
from timeit import timeit
run_time = timeit(lambda: subprocess.call(['gnuplot', 'sript.gnuplot']), number=1)
print 'run_time: %.1f milliseconds' % (run_time*1000)

请注意,这会将运行时间作为数字提供给您,而您必须自己从 time 的输出字符串 (0.65user 0.06system 0:00.72elapsed) 中提取它。

【讨论】:

  • 好多了!如您所料,我想操作字符串,这将是不必要的麻烦。
猜你喜欢
  • 2018-07-09
  • 2019-08-13
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多