【问题标题】:How to know the execution time in linux如何知道linux中的执行时间
【发布时间】:2014-03-15 15:52:13
【问题描述】:

假设我有三个脚本(a.sh b.sh c.sh)要在一个名为launcher.sh的脚本中启动:

first=`date +%s`

./a.sh &
./b.sh &
./c.sh &

final=`date +%s`

executionTime=`echo "scale=3;($final - $first)/3600" | bc`

echo $executionTime

我知道上面的脚本不会工作,因为 launcher.sh 将在启动 a.sh、b.sh 和 c.sh 后立即完成。在没有 "&" 的情况下启动 a.sh、b.sh 和 c.sh 是在浪费时间,因为它们不必相互等待。

假设它们的执行时间分别为 5 秒、10 秒和 7 秒,我怎样才能得到 10 秒作为整体执行时间?

【问题讨论】:

    标签: linux bash shell scheduled-tasks fork


    【解决方案1】:

    使用wait:

    first=`date +%s`
    
    ./a.sh &
    ./b.sh &
    ./c.sh &
    
    wait
    
    ...
    

    引用help wait:

    wait: wait [id]

    Wait for job completion and return exit status.
    
    Waits for the process identified by ID, which may be a process ID or a
    job specification, and reports its termination status.  If ID is not
    given, waits for all currently active child processes, and the return
    status is zero.  If ID is a a job specification, waits for all processes
    in the job's pipeline.
    
    Exit Status:
    Returns the status of ID; fails if ID is invalid or an invalid option is
    given.
    

    【讨论】:

    • @Mat 感谢您教我一些关于降价的新知识。 (我想知道为什么更改没有任何效果。)
    • 对了,我可以要求更多吗?手册说等待当前活动的子进程,但是有没有可能子进程不是活动的?如果子进程调用睡眠,那是一个活动进程吗?
    • 如果它调用睡眠,它仍然被认为是活跃的。
    • @MarcusThornton 正如 Johannes 所说,即使您正在调用 sleep,它也会激活。这里的active指的是一个正在运行的进程。
    • @MarcusThornton 甚至 blocked(在进程控制方面)和 zombie 进程都将被视为活动的。基本上,每个没有被安排到stopped(通常是通过发送sigterm)的进程都是。
    【解决方案2】:

    linux 附带了time 命令,该命令专为这种确切用途而设计。只需致电time yourscript

    当您的启动器脚本在后台启动进程时,仅time 是不够的。正如@devnull 所说,wait 命令会阻止调用,直到所有子进程都终止。

    有一种简单的方法可以将等待和时间结合起来,无需修改启动器脚本,也无需手动停止时间:

    time `./launcher.sh;wait `
    

    应该可以解决问题。

    (用一个最小的例子试过这个。只要你在子shell中执行启动器+等待(使用``),这将起作用(但是如果它确实输出了一些东西,你会从launcherh脚本中丢失otuput))


    小例子:

    test1.sh

    ./test2.sh &
    

    test2.sh

    sleep 10
    

    结果:

    $时间`./test1.sh;wait`

    真正的 0m10.004s
    用户 0m0.001s
    系统 0m0.001s

    【讨论】:

    • @devnull erm... 必须同意这一点。我将编辑此答案以反映这一点,并提供一个工作解决方案。
    • 我已经尝试了@JohannesH 的解决方案。提到使用时间,它没有工作。
    • @MarcusThornton 查看我的编辑。它基本上是 devnull 建议和我原来的解决方案的组合(所以也相信他)。我对此进行了测试,它应该可以工作,并且是恕我直言的最简单方法。
    • test.sh: sleep 20 test2.sh: ./test.sh & time ./test2.sh;wait real 0m0.005s user 0m0.002s sys 0m0.001s 好像不行
    • 我用 2 个脚本对此进行了测试:一个是 sleep 10,另一个调用第一个(当然,它使用 & 进行了守护)。我的答案中的命令在 10 秒后显示 10 秒运行时间。
    【解决方案3】:

    就在退出脚本之前编写

    echo $SECONDS
    

    或在终端窗口中运行您的脚本,输入

    $> time your_script
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多