简体   繁体   English

在python中执行linux time命令

[英]Executing linux time command inside python

I want to calculate the time taken to execute ac program inside a python script. 我想计算在python脚本中执行ac程序所花费的时间。 I used os.system() function for this. 我为此使用了os.system()函数。

os.system("{ time ./test.out < inp;} > out 2> exe_time")
  • test.out is my c executable test.out是我的c可执行文件
  • inp contains input for c inp包含c的输入
  • out stores the output of c program 输出存储c程序的输出
  • exe_time stores the execution time of the program. exe_time存储程序的执行时间。

The result I get in exe_time is something like this 我在exe_time中得到的结果是这样的

0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 1416maxresident)k 0inputs+8outputs (0major+65minor)pagefaults 0swaps 0.00user 0.00系统0:00.00经过?%CPU(0avgtext + 0avgdata 1416maxresident)k 0输入+ 8输出(0major + 65minor)页面错误0交换

But when I execute { time ./test.out < inp;} > out 2> exe_time in terminal I get in the exe_time file 但是当我在终端执行{time ./test.out <inp;}> out 2> exe_time时,我进入了exe_time文件

real 0m0.001s 真实的0m0.001s
user 0m0.000s 用户0m0.000s
sys 0m0.000s sys 0m0.000s

How do I get the second version of output by using python? 如何使用python获取输出的第二版本?

Invoke your code with bash , not /bin/sh (as is default for system() ): 使用bash而不是/bin/sh调用代码(这是system()默认设置):

subprocess.Popen(['bash', '-c', '{ time ./test.out < inp;} > out 2> exe_time'])

Note however that the above code is not safe to parameterize to work with arbitrary filenames. 但是请注意,上述代码无法安全地参数化以使用任意文件名。 A better-practices implementation might instead look like: 更好的做法可能是:

o, e = subprocess.Popen(['bash', '-c', 'time "$@" 2>&1', '_', './test.out'],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

print("Output from command is:")
sys.stdout.write(o + "\n")
print("Output from time is:")
sys.stdout.write(e + "\n")

Note: 注意:

  • We're explicitly invoking bash , and thus ensuring that its built-implementation of time is used. 我们正在显式调用bash ,从而确保使用其内置的time实现。
  • Passing arguments out-of-band from the shell script makes it safe to pass arbitrary arguments to the script being run without worrying about whether those arguments contain attempted shell injection attacks. 从shell脚本带外传递参数可以安全地将任意参数传递给正在运行的脚本,而不必担心这些参数是否包含尝试的shell注入攻击。
  • Redirecting 2>&1 within the shell script ensures that any stderr written by test.out is joined with other output, not mixed in with the output from the time command. 在shell脚本中重定向2>&1可以确保将test.out编写的任何stderr与其他输出合并,而不是与time命令的输出混合。
  • If we did want to redirect output to files, the better-practice approach would be to do that from Python, as with stdout=open('out', 'w'), stderr=open('exe_time', 'w') . 如果我们确实想将输出重定向到文件,则更好的做法是从Python执行此操作,例如stdout=open('out', 'w'), stderr=open('exe_time', 'w')

os.system() uses /bin/sh . os.system()使用/bin/sh Bash has its own time builtin that it uses instead of the time binary: Bash有自己的内置time ,而不是time二进制文件:

$ /usr/bin/time ls /asd
ls: /asd: No such file or directory
        0.00 real         0.00 user         0.00 sys
$ time ls /asd
ls: /asd: No such file or directory

real    0m0.018s
user    0m0.008s
sys     0m0.013s

If you want to see how long it takes for a command to be executed, just use subprocess : 如果要查看执行命令需要多长时间,只需使用subprocess

import time
import subprocess

with open('inp', 'rb') as input_file:
    with open('out', 'wb') as output_file:
        start = time.time()
        subprocess.call(['./test.out'], stdin=input_file, stdout=output_file)
        runtime = time.time() - start

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM