Skip to content

Commit aac1168

Browse files
authored
Merge pull request #27 from tmck-code/20250519_get_unix_time_fast_with_pure_bash
add article: Get unix time FAST with pure bash
2 parents ea1cebf + d561d12 commit aac1168

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ my blog
44

55
---
66

7+
### [20250519 Get unix time FAST with pure bash](articles/20250519_get_unix_time_fast_with_pure_bash/20250519_get_unix_time_fast_with_pure_bash.md)
8+
9+
> _Faster than the beloved `date +%s`_
10+
711
### [20250506 Dictionary slice in Python](articles/20250506_dictionary_slice_in_python/20250506_dictionary_slice_in_python.md)
812

913
> _Creating an equivalent of Ruby's 'Hash.slice' in python_
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# 20250519 Get unix time FAST with pure bash
2+
3+
```shell
4+
printf '%(%s)T\n' -1
5+
```
6+
7+
> _Beware! There are a few different versions of `printf` that could be installed on your machine:_
8+
9+
```shell
10+
type -a printf
11+
printf is a shell builtin
12+
printf is /usr/bin/printf
13+
printf is /bin/printf
14+
```
15+
16+
The speed of this time command comes from the fact that it's a shell builtin and doesn't require forking a new process.
17+
18+
I'm too dumb to figure out how to benchmark this inline using `hyperfine`, so I just created 2 files with the commands and made them executable with `chmod +x`:
19+
20+
```shell
21+
☯ cat date.sh
22+
#!/bin/bash
23+
date +%s
24+
25+
☯ cat printf.sh
26+
#!/bin/bash
27+
printf '%(%s)T\n' -1
28+
29+
```
30+
## Results
31+
32+
![benchmark](image.png)
33+
34+
_On the same machine, it takes `0.9` seconds to run a file that is completely empty (apart from the shebang), which leaves the `printf` command as being almost instant 🚀_
50.1 KB
Loading

0 commit comments

Comments
 (0)