Discussion:
Is $(exec external_cmd.sh) always preferred over $(external_cmd.sh)?
(too old to reply)
Peng Yu
2018-11-13 23:27:50 UTC
Permalink
Hi,

See the following example, the $() with exec seems to be faster the
one without exec. But there is always fluctuation of my test results.
Is the exec version always preferred? (Besides run time, another
benefit I know is it reduce one process as well.)

$ ./main_performance.sh
tmpfile=$(mktemp -u)
time for((i=0;i<1000;++i))
do
x=$(./script.sh)
done # > "$tmpfile"

real 0m9.861s
user 0m2.824s
sys 0m5.488s
tmpfile=$(mktemp -u)
time for((i=0;i<1000;++i))
do
x=$(exec ./script.sh)
done # > "$tmpfile"

real 0m9.525s
user 0m2.781s
sys 0m5.245s

$ cat script.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

echo "$BASHPID"
--
Regards,
Peng
Eduardo Bustamante
2018-11-14 02:16:29 UTC
Permalink
Post by Peng Yu
Hi,
See the following example, the $() with exec seems to be faster the
one without exec. But there is always fluctuation of my test results.
Is the exec version always preferred? (Besides run time, another
benefit I know is it reduce one process as well.)
$ ./main_performance.sh
tmpfile=$(mktemp -u)
time for((i=0;i<1000;++i))
do
x=$(./script.sh)
done # > "$tmpfile"
real 0m9.861s
user 0m2.824s
sys 0m5.488s
tmpfile=$(mktemp -u)
time for((i=0;i<1000;++i))
do
x=$(exec ./script.sh)
done # > "$tmpfile"
real 0m9.525s
user 0m2.781s
sys 0m5.245s
(...)

The difference between the two is 336ms. So that means that you save
336us per iteration. What kind of script are you implementing that
you're worried about a 336us overhead? is it really worth making your
code less readable just to shave 336us per command substitution?
konsolebox
2018-11-14 06:29:28 UTC
Permalink
Post by Peng Yu
Is the exec version always preferred?
Bash skips another fork inside command substitution when command is just
simple. No need to use exec.
Loading...