子进程检查输出剪切我的输出

2024-04-26 21:07:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须使用以下方法编写几个C程序在几个文件上运行所需的时间:

time ./program filename

我用subprocess.check_outputstdout作为字符串。我应该从以下几点入手:

real    0m0.001s
user    0m0.001s
sys     0m0.000s

但我得到:

b'0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 
1388maxresident)k\n0inputs+0outputs (0major+60minor)pagefaults 
0swaps\n'

我看到了用户和系统时间,但它们在小数点后两位被截断。有没有办法确保输出读取所有3个小数位? 这是我的密码:

import xlwt
import subprocess

files = ('100KB.txt', '1MB.txt', '10MB.txt', '100MB.txt')
programs = ('./10kBuffer', './step2', './step3', './step4')

command = ['time', programs[0], files[0]]
out = subprocess.check_output(command, stderr=subprocess.STDOUT)
print(out)

Tags: 文件方法import程序txtoutputtimecheck
2条回答

这是因为GNUtime使用了更详细的默认格式字符串,但您需要-p选项。你知道吗

引用manual

The default format string is:

%Uuser %Ssystem %Eelapsed %PCPU (%Xtext+%Ddata %Mmax)k %Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps

When the -p option is given, the (portable) output format is used:

real %e
user %U
sys %S

您还需要对输出进行解码,否则将得到bytes而不是str,并且不会解释换行符。例如:

>>> print(b'hello\nworld\n')
b'hello\nworld\n'
>>> print('hello\nworld\n')
hello
world

所以我会按原样修复你的代码:

command = ['time', '-p', programs[0], files[0]]
out = subprocess.check_output(command, stderr=subprocess.STDOUT)
print(out.decode())

EDIT:the other answer似乎可以通过使用shell内置来帮助修复丢失的小数。你可以把两个答案混合起来,得到你所需要的字符串输出,并且有足够的小数。你知道吗

请注意,除非您想为您的命令使用探查器,否则您似乎不能做得更好(请参见How do I get time of a Python program's execution?

看起来您正在混淆python脚本使用的GNUtime和命令行上使用的timeshell内置程序。你知道吗

这来自GNUtime的手册页:

Note: some shells (e.g., bash(1)) have a built-in time command that provides less functionality than the command described here. To access the real command, you may need to specify its pathname (something like /usr/bin/time).

根据您所期望的输出,看起来您想要的是bash内置,它给出了3位小数:

$ bash -c time time

real    0m0.000s
user    0m0.000s
sys     0m0.000s

$ sh -c time time
user    0m0.00s
sys     0m0.00s

$ ksh -c time time
user    0m0.00s
sys     0m0.00s

$ tcsh -c time time
0.016u 0.011s 0:00.02 100.0%    0+0k 0+0io 0pf+0w

因此,为了指定bash内置而不是GNUtime,您可以将命令更改为:

command = ['bash', '-c', 'time', programs[0], files[0]]

你应该得到你期望的结果。你知道吗

相关问题 更多 >