作为评估的一部分,我想测量和比较不同diff工具的用户+系统运行时。
作为第一种方法,我考虑用time - f
(GNUtime
)调用特定的工具。由于其余的评估是由一堆Python脚本完成的,所以我想用Python实现它。在
时间输出的格式如下:
<some error message>
user 0.4
sys 0.2
diff工具的输出被重定向到sed
,以消除不需要的输出,sed
的输出随后被进一步处理。(在我的示例中,不推荐使用sed
。请参见编辑2)
从shell中进行的调用如下所示(删除以“Binary”开头的行):
^{pr2}$到目前为止,我的方法是:
import subprocess
diffcommand=["time","-f","user %U\nsys %S\n","diff","-r","-u0","testrepo_1/A/rev","testrepo_1/B/rev"]
sedcommand = ["sed","-e","/^Binary.*/d"]
# Execute command as subprocess
diff = subprocess.Popen(diffcommand, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
# Calculate runtime
runtime = 0.0
for line in diff.stderr.readlines():
current = line.split()
if current:
if current[0] == "user" or current[0] == "sys":
runtime = runtime + float(current[1])
print "Runtime: "+str(runtime)
# Pipe to "sed"
sedresult = subprocess.check_output(sedcommand, stdin=diff.stdout)
# Wait for the subprocesses to terminate
diff.wait()
然而,感觉这并不干净(特别是从操作系统的角度来看)。这也会导致脚本在某些情况下被困在readlines
部分,我还不知道。在
有没有更干净(或更好)的方法来实现我想要的?在
编辑1 换了头线,做了更详细的解释
编辑2
感谢J.F.Sebastian,我查看了os.wait4(...)
(信息来自{a1})。但是,由于我对输出感兴趣,我不得不实现它有点不同。在
我的代码现在如下所示:
diffprocess = subprocess.Popen(diffcommand,stdout=subprocess.PIPE)
runtimes = os.wait4(diffprocess.pid,0)[2]
runtime = runtimes.ru_utime + runtimes.ru_stime
diffresult = diffprocess.communicate()[0]
注意,我不再通过管道将结果发送到sed
(决定在python中修剪)
运行时度量在某些测试用例中运行良好,但有时执行会卡住。删除运行时度量将帮助程序终止,并将stdout
发送到DEVNULL
(按要求here)。能给我个僵局吗?(valgrind --tool=helgrind
没有发现任何问题)我的方法是否存在根本性的错误?在
如果使用
stdout=PIPE
,则当进程仍在运行时,某个应该读取输出,否则,如果子进程的stdout OS管道缓冲区填满(在我的机器上为65K),则子进程将挂起。在相关问题 更多 >
编程相关推荐