Skip to content

Commit 58d72da

Browse files
committed
refactor: improve clock performance
1 parent fd4d277 commit 58d72da

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

src/clock.sh

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
#!/usr/bin/env bash
22

33
function clock::now() {
4+
local shell_time
5+
if shell_time="$(clock::shell_time)"; then
6+
local seconds="${shell_time%%.*}"
7+
local microseconds="${shell_time#*.}"
8+
9+
math::calculate "($seconds * 1000000000) + ($microseconds * 1000)"
10+
return 0
11+
fi
12+
413
if dependencies::has_perl && perl -MTime::HiRes -e "" > /dev/null 2>&1; then
514
if perl -MTime::HiRes -e 'printf("%.0f\n",Time::HiRes::time()*1000000000)'; then
615
return 0
@@ -27,18 +36,6 @@ function clock::now() {
2736
fi
2837
fi
2938

30-
local shell_time has_shell_time
31-
shell_time="$(clock::shell_time)"
32-
has_shell_time="$?"
33-
if [[ "$has_shell_time" -eq 0 ]]; then
34-
local seconds microseconds
35-
seconds=$(echo "$shell_time" | cut -f 1 -d '.')
36-
microseconds=$(echo "$shell_time" | cut -f 2 -d '.')
37-
38-
math::calculate "($seconds * 1000000000) + ($microseconds * 1000)"
39-
return 0
40-
fi
41-
4239
echo ""
4340
return 1
4441
}

tests/unit/clock_test.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,15 @@ function mock_non_existing_fn() {
1515
}
1616

1717
function test_now_with_perl() {
18+
mock clock::shell_time mock_non_existing_fn
1819
mock perl echo "1720705883457"
1920

2021
assert_same "1720705883457" "$(clock::now)"
2122
}
2223

2324
function test_now_on_linux_unknown() {
2425
mock_unknown_linux_os
26+
mock clock::shell_time mock_non_existing_fn
2527
mock perl mock_non_existing_fn
2628
mock date echo "1720705883457"
2729

@@ -30,6 +32,7 @@ function test_now_on_linux_unknown() {
3032

3133
function test_now_on_linux_alpine() {
3234
mock_alpine_os
35+
mock clock::shell_time mock_non_existing_fn
3336
mock perl echo "1720705883457"
3437

3538
assert_same "1720705883457" "$(clock::now)"
@@ -40,6 +43,7 @@ function test_now_on_windows_without_with_powershell() {
4043
mock dependencies::has_perl mock_false
4144
mock dependencies::has_powershell mock_true
4245
mock powershell echo "1727768183281580800"
46+
mock clock::shell_time mock_non_existing_fn
4347

4448
assert_same "1727768183281580800" "$(clock::now)"
4549
}
@@ -49,6 +53,7 @@ function test_now_on_windows_without_without_powershell() {
4953
mock dependencies::has_perl mock_false
5054
mock dependencies::has_powershell mock_false
5155
mock date echo "1727768951"
56+
mock clock::shell_time mock_non_existing_fn
5257

5358
assert_same "1727768951" "$(clock::now)"
5459
}

0 commit comments

Comments
 (0)