Xpl0 Xpl0 - 4 months ago 12
Python Question

Force "time" command format

For some reason, when I run "time ./" from the terminal, I get this format:

real 0m0.090s
user 0m0.086s
sys 0m0.004s

but when I execute the same command on Python

result = subprocess.Popen("time ./<binary>", shell = True, stdout = subprocess.PIPE)

then I get this format:

0.09user 0.00system 0:00.09elapsed

Is there any way I can force the first (real, user, sys) format?


From the man time documentation:

After the utility finishes, time writes the total time elapsed, the time consumed by system overhead, and the time used to execute utility to the standard error stream.

Bold emphasis mine. You are capturing the stdout stream, not the stderr stream, so whatever output you see must be the result of something else mangling your Python stderr stream.

Capture stderr:

proc = subprocess.Popen("time ./<binary>", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

The stderr variable then holds the time command output.

If this continues to produce the same output, your /bin/bash implementation has a built-in time command that overrides the /usr/bin/time version (which probably outputs everything on one line). You can force the use of the bash builtin by telling Python to run with that:

proc = subprocess.Popen("time ./<binary>", shell=True, executable='/bin/bash',
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()