clocking subprocesses

Matt Nordhoff mnordhoff at mattnordhoff.com
Mon Mar 3 18:02:50 EST 2008


barnburnr at gmail.com wrote:
> On Mar 3, 12:41 pm, Preston  Landers <pland... at gmail.com> wrote:
>> Run your command through the "time" program.  You can parse the output
>> format of "time", or set a custom output format.  This mostly applies
>> to Unix-like systems but there is probably an equivalent somewhere on
>> Windows.
>>
>> Preston
> 
> Thanks for the quick answer.  That seems to work, though, I'll write a
> timesubprocess() function which runs the program through time and
> spits the formatted out to a file, then parses that file, then returns
> the execution time.  There doesn't appear to be a more elegant way to
> do this.
> 
> Kevin

subprocess can do that easily.

What about something like this?

def timecall(args):
    p = subprocess.Popen(['time', '--format', '%e %U %S'] + args,
                         stderr=subprocess.PIPE)
    p.wait()
    timings = p.stderr.readline().split()
    assert len(timings) == 3
    timings = tuple(float(t) for t in timings)
    return timings

It returns (real, user, sys), in seconds. The program's stdout goes to
sys.stdout, I don't know where the program's stderr goes, and it really
doesn't handle errors, but it's got the basic idea.
-- 



More information about the Python-list mailing list