Skip to content

Instantly share code, notes, and snippets.

@jcelliott
Created August 25, 2014 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcelliott/f39abedee3480ad298f8 to your computer and use it in GitHub Desktop.
Save jcelliott/f39abedee3480ad298f8 to your computer and use it in GitHub Desktop.
A small binary to print a duration in milliseconds in a human-friendly format
package main
import (
"fmt"
"os"
"strconv"
)
const (
MIN = 60
HOUR = MIN * 60
DAY = HOUR * 24
)
func main() {
// duration is time in milliseconds
if len(os.Args) != 2 || os.Args[1] == "-h" || os.Args[1] == "--help" || os.Args[1] == "-help" {
fmt.Printf("usage: %s [-h] <milliseconds>\n", os.Args[0])
os.Exit(1)
}
duration, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Printf("%s\n\nusage: %s [-h] <milliseconds>\n", err, os.Args[0])
os.Exit(1)
}
seconds := float64(duration) / 1000
if seconds < 1 {
fmt.Printf("%dms\n", duration)
} else if seconds < MIN {
fmt.Printf("%.1fs\n", seconds)
} else if seconds < HOUR {
fmt.Printf("%dm %ds\n", int(seconds)/MIN, int(seconds)%MIN)
} else if seconds < DAY {
if int(seconds)%MIN >= 30 {
// round up to nearest minute
seconds += MIN
}
fmt.Printf("%dh %dm\n", int(seconds)/HOUR, int(seconds)%HOUR/MIN)
} else {
if int(seconds)%MIN >= 30 {
// round up to nearest minute
seconds += MIN
}
fmt.Printf("%dd %dh %dm\n", int(seconds)/DAY, int(seconds)%DAY/HOUR, int(seconds)%HOUR/MIN)
}
}
@jcelliott
Copy link
Author

I use this with fish shell to print the duration of long-running commands when they finish.

@jcelliott
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment