I'm working on a script where execution speed is crucial. Manually adding `time` to the start of every line to check where I need to optimize isn't practical for me. Is there a tool or method that can effectively track execution time for each line in my script and generate a report on the timings?
3 Answers
You can use debugging options in Bash to measure execution time. Setting `PS4` to include timestamps can help. Try this:
```
export PS4='+($(date +%s.%N)) '
set -x
# Your script starts here
echo "Hello"
sleep 1
echo "World"
```
This way, you'll see the timestamps for each command in the output, although be cautious as it can slow things down a bit.
There's a Bash profiler project called bash-boost that you might find helpful. It won't give you perfect accuracy, but it's good for highlighting where most of the time is spent in your script. You can check it out on GitHub.
If you need fine-grained timing, consider redefining your functions to use `time`. For example, you could wrap commands like this:
```
FOO() { time command FOO "$@"; }
BAR() { time command BAR "$@"; }
```
This way, you can specify which functions to time without affecting everything all at once.
That's a creative approach! It gives you flexibility by targeting specific commands instead of timing the whole script.

Just a heads up, using `$(date +%s.%N)` can really bog down your script since it spawns a subshell. A more efficient way is using `$EPOCHREALTIME`, which won't add that much delay.