github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/cmds/exp/rush/time.go (about)

     1  // Copyright 2012 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Time process execution.
     6  //
     7  // Synopsis:
     8  //     time CMD [ARG]...
     9  //
    10  // Description:
    11  //     After executing CMD, its real, user and system times are printed to
    12  //     stderr in the POSIX format.
    13  //
    14  //     CMD can be a builtin, e.g. time cd
    15  //
    16  // Example:
    17  //     $ time sleep 1.23s
    18  //     real 1.230
    19  //     user 0.001
    20  //     sys 0.000
    21  //
    22  // Note:
    23  //     This is different from bash's time command which is built into the shell
    24  //     and can time the entire pipeline.
    25  //
    26  // Bugs:
    27  //     Time is not reported when exiting due to a signal.
    28  package main
    29  
    30  import (
    31  	"fmt"
    32  	"os"
    33  	"os/exec"
    34  	"time"
    35  )
    36  
    37  func init() {
    38  	addBuiltIn("time", runtime)
    39  }
    40  
    41  func printTime(label string, t time.Duration) {
    42  	fmt.Fprintf(os.Stderr, "%s %.03f\n", label, t.Seconds())
    43  }
    44  
    45  func runtime(c *Command) error {
    46  	var err error
    47  	start := time.Now()
    48  	if len(c.argv) > 0 {
    49  		c.cmd = c.argv[0]
    50  		c.argv = c.argv[1:]
    51  		c.args = c.args[1:]
    52  		// If we are in a builtin, then the lookup failed.
    53  		// The result of the failed lookup remains in
    54  		// c.Cmd and will make start fail. We have to make
    55  		// a new Cmd.
    56  		nCmd := exec.Command(c.cmd, c.argv[:]...)
    57  		nCmd.Stdin = c.Stdin
    58  		nCmd.Stdout = c.Stdout
    59  		nCmd.Stderr = c.Stderr
    60  		c.Cmd = nCmd
    61  		err = runit(c)
    62  	}
    63  	realTime := time.Since(start)
    64  	printTime("real", realTime)
    65  	if c.ProcessState != nil {
    66  		printTime("user", c.ProcessState.UserTime())
    67  		printTime("sys", c.ProcessState.SystemTime())
    68  	}
    69  	return err
    70  }