Skip to content

Instantly share code, notes, and snippets.

@taikedz
Last active June 3, 2025 08:51
Show Gist options
  • Save taikedz/9e9f940ef5f3320d5b3b5eac3eb6bd7d to your computer and use it in GitHub Desktop.
Save taikedz/9e9f940ef5f3320d5b3b5eac3eb6bd7d to your computer and use it in GitHub Desktop.
Process Timer in Go
/* Print the wall-clock time of the duration of a subprocess.
*
* Linux `time` command frequently writes strange output formatting on console if attempting to store
* the result, and it's sometimes also hard to dissociate it from the program outputs.
*
* This simple program runs a command, dumping its output, and then writes the duration to a file.
*/
package main
import (
"fmt"
"time"
"os/exec"
"os"
"bufio"
"log"
"strings"
"io"
)
func main() {
if len(os.Args) < 3 {
fmt.Printf("%s TIMERFILE COMMAND ...\n", os.Args[0])
os.Exit(1)
}
t0 := time.Now()
status := runCommand(os.Args[2], os.Args[3:]...)
t1 := time.Now()
writeTime(os.Args[1], t1.Sub(t0), strings.Join(os.Args[2:], " "))
os.Exit(status)
}
func writeTime(filename string, tdiff time.Duration, command string) {
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatal("Could not open timings.txt file")
}
defer f.Close()
message := fmt.Sprintf("[%v] : %s\n", tdiff, command)
if _, err = f.WriteString(message); err != nil {
log.Fatal("Could not write timing")
}
}
func RunCmd(cmd string, args ... string) error {
cmd := exec.Command(cmd, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Printf("Execution error: %v\n", err)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment