Skip to content

Commit

Permalink
New function duration
Browse files Browse the repository at this point in the history
  • Loading branch information
kigster committed Mar 8, 2022
1 parent d54d265 commit bd67ef2
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.6.0
2.6.1
17 changes: 17 additions & 0 deletions lib/time.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env bash
# vim: set ft=bash
#——————————————————————————————————————————————————————————————————————————————
# © 2016-2021 Konstantin Gredeskoul, All rights reserved. MIT License.
# Ported from the licensed under the MIT license Project Pullulant, at
Expand Down Expand Up @@ -88,6 +90,21 @@ function time.with-duration() {
time.with-duration.end "$@"
}

# @description
# This function receives a command to execute as an argument.
# The command is executed as 'eval "$@"'; meanwhile the start/end
# times are measured, and the following string is printed at the end:
# eg. "4 minutes 24.345 seconds"
# @args Command to run
function duration() {
local start="$(millis)"
eval "$@"
local end="$(millis)"
local ruby_expr="secs=(0.0 + ${end} - ${start}).to_f/1000.0; mins=secs/60; secs=( secs - secs/60 ) if mins > 0 ; printf('%d minutes %2.3f seconds', mins, secs)"
local duration=$(ruby -e "${ruby_expr}")
echo -en "${duration}"
}

# Returns the date command that constructs a date from a given
# epoch number. Appears to be different on linux vs OSX.
time.date-from-epoch() {
Expand Down
9 changes: 9 additions & 0 deletions test/time_test.bats
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ source lib/time.sh
source lib/util.sh
source lib/user.sh

# duration 'sleep 1.1'
# 0 minutes 1.100 seconds
@test 'duration' {
set -e
duration 'sleep 1.1' | grep -E -q "0 minutes 1.\d\d\d seconds"
}

@test "time.with-duration()" {
time.with-duration.start
sleep 0.1
Expand Down Expand Up @@ -79,3 +86,5 @@ source lib/user.sh
[[ $(time.duration.humanize 1644) == "27m:24s" ]]
[[ $(time.duration.humanize 1646324) == "457h:18m:44s" ]]
}


0 comments on commit bd67ef2

Please sign in to comment.