get how much time python subprocess spends

后端 未结 3 1733
一整个雨季
一整个雨季 2021-02-19 01:04

I\'d like to time how long does the subprocess take. I tried to use

start = time.time()
subprocess.call(\'....\')
elapsed = (time.time() - start)
3条回答
  •  春和景丽
    2021-02-19 01:17

    It took me a little while to implement Roland's solution due to the annoyingness of passing around python code as strings, so I thought I'd share a working example.

    This script times an external program in the working directory, and redirects its standard output and standard error to files.

    from timeit import timeit
    
    reps = 500
    stdout = open("add_numbers_outputs.log", 'w')
    stderr = open("add_numbers_errors.log", 'w')
    external_command = "./add_numbers"
    parameter = str(1000000) # one million
    
    call_arguments = """[
            '%s',
            '%s'], # pass additional parameters by adding elements to this list
            stdout=stdout,
            stderr=stderr
    """ % (external_command, parameter)
    
    print "Timing external command "+external_command+" with parameter "+parameter
    
    time_taken = timeit(stmt = "subprocess.call(%s)" % call_arguments,
            setup = """import subprocess;
    stdout = open("add_numbers_outputs.log", 'w');
    stderr = open("add_numbers_errors.log", 'w')
    """,
            number = reps) / reps
    
    print "Average time taken for %s repetitions: %f seconds" % (reps, time_taken)
    

提交回复
热议问题