Skip to content

Commit bd67ef2

Browse files
committed
New function duration
1 parent d54d265 commit bd67ef2

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

.version

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
2.6.0
1+
2.6.1

lib/time.sh

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#!/usr/bin/env bash
2+
# vim: set ft=bash
13
#——————————————————————————————————————————————————————————————————————————————
24
# © 2016-2021 Konstantin Gredeskoul, All rights reserved. MIT License.
35
# Ported from the licensed under the MIT license Project Pullulant, at
@@ -88,6 +90,21 @@ function time.with-duration() {
8890
time.with-duration.end "$@"
8991
}
9092

93+
# @description
94+
# This function receives a command to execute as an argument.
95+
# The command is executed as 'eval "$@"'; meanwhile the start/end
96+
# times are measured, and the following string is printed at the end:
97+
# eg. "4 minutes 24.345 seconds"
98+
# @args Command to run
99+
function duration() {
100+
local start="$(millis)"
101+
eval "$@"
102+
local end="$(millis)"
103+
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)"
104+
local duration=$(ruby -e "${ruby_expr}")
105+
echo -en "${duration}"
106+
}
107+
91108
# Returns the date command that constructs a date from a given
92109
# epoch number. Appears to be different on linux vs OSX.
93110
time.date-from-epoch() {

test/time_test.bats

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@ source lib/time.sh
77
source lib/util.sh
88
source lib/user.sh
99

10+
# duration 'sleep 1.1'
11+
# 0 minutes 1.100 seconds
12+
@test 'duration' {
13+
set -e
14+
duration 'sleep 1.1' | grep -E -q "0 minutes 1.\d\d\d seconds"
15+
}
16+
1017
@test "time.with-duration()" {
1118
time.with-duration.start
1219
sleep 0.1
@@ -79,3 +86,5 @@ source lib/user.sh
7986
[[ $(time.duration.humanize 1644) == "27m:24s" ]]
8087
[[ $(time.duration.humanize 1646324) == "457h:18m:44s" ]]
8188
}
89+
90+

0 commit comments

Comments
 (0)