how to measure command execution time in linux and give result as single number (seconds…
- User
how to measure command execution time in linux and give result as single number (seconds or milliseconds)
- Assistant
how to measure command execution time in linux and give result as single number (seconds or milliseconds)
To measure command execution time in Linux and get the result as a single number (in seconds or milliseconds), you can use a few methods:
time command with formattingThe time command can measure execution time. The builtin time output is verbose, but the external /usr/bin/time supports formatting.
Example:
/usr/bin/time -f "%e" your_command
%e prints elapsed real time (wall clock) in seconds with milliseconds as decimal (e.g., 1.23).Example:
/usr/bin/time -f "%e" sleep 1.5
Output:
1.50
Note: Make sure you use the external time, not the shell builtin.
Check by:
type time
If time is a shell keyword, use /usr/bin/time explicitly.
date or bash built-in variables (for millisecond precision)If /usr/bin/time is not available or formatting is not flexible, you can do:
start=$(date +%s%3N)
your_command
end=$(date +%s%3N)
echo $((end - start))
%s%3N is seconds + milliseconds since epoch (GNU date extension).Example:
start=$(date +%s%3N)
sleep 1
end=$(date +%s%3N)
echo $((end - start)) # outputs close to 1000
bash with SECONDS variable (seconds only with fractions require bash 5+)SECONDS is a bash variable that counts seconds since shell started or reset.
SECONDS=0
your_command
echo $SECONDS
This gives elapsed seconds as integer.
Bash 5+ supports fractional SECONDS but on many systems it’s integer.
| Method | Precision | Output Unit | Usage |
|---|---|---|---|
/usr/bin/time -f "%e" | Fractional seconds | Seconds (float) | /usr/bin/time -f "%e" command |
date +%s%3N diff | Milliseconds | Milliseconds | Use bash arithmetic with start/end times |
Bash SECONDS variable | Seconds (int) | Seconds | SECONDS=0; command; echo $SECONDS |
If you want a single numeric value in seconds with decimals, the first method is straightforward and best.
If you want milliseconds as integer, the second method works.
start=$(date +%s%3N)
sleep 1.234
end=$(date +%s%3N)
elapsed=$((end - start))
echo $elapsed # Output: approx 1234
Let me know if you want the solution wrapped into a function or with other requirements!
Not yet included in a published release.