Advertisement
devinteske

Ultra-fast internal which replacement for sh(1)

Jul 10th, 2013
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.79 KB | None | 0 0
  1. #!/bin/sh
  2. : ${STRESS=10000}
  3. SUCCESS=0
  4. FAILURE=1
  5. f_which()
  6. {
  7.     local __name="$1" __var_to_set="$2"
  8.     case "$__name" in */*|'') return $FAILURE; esac
  9.     if [ "$__var_to_set" ]; then
  10.         # Do this without a sub-shell to keep things fast
  11.             local __p IFS=":"
  12.             for __p in $PATH; do
  13.                     local __exec="$__p/$__name"
  14.                     [ -f "$__exec" -a -x "$__exec" ] &&
  15.                 setvar "$__var_to_set" "$__exec" &&
  16.                 return $SUCCESS
  17.             done
  18.         else
  19.         # Take a short-cut through the `hash' built-in
  20.         type "$__name" > /dev/null 2>&1 &&
  21.             hash -v "$__name" 2> /dev/null
  22.     fi
  23. }
  24. if [ $# -ge 2 ]; then
  25.     if [ ! "$STRESS" ]; then
  26.         f_which "$1" "$2"
  27.         retval=$?
  28.         eval echo \"\$2=[\$$2]\"
  29.         exit $retval
  30.     else
  31.         echo -n "Stressing f_which... "
  32.         n=0
  33.         start_epoch=$( date +%s )
  34.         while [ $n -lt $STRESS ]; do
  35.             f_which "$1" "$2"
  36.             n=$(( $n + 1 ))
  37.         done
  38.         end_epoch=$( date +%s )
  39.         echo "$(( $end_epoch - $start_epoch )) seconds ($STRESS runs)"
  40.  
  41.         echo -n "Stressing which... "
  42.         n=0
  43.         start_epoch=$( date +%s )
  44.         while [ $n -lt $STRESS ]; do
  45.             name=$( which "$1" )
  46.             n=$(( $n + 1 ))
  47.         done
  48.         end_epoch=$( date +%s )
  49.         echo "$(( $end_epoch - $start_epoch )) seconds ($STRESS runs)"
  50.     fi
  51. else
  52.     if [ ! "$STRESS" ]; then
  53.         f_which "$1"
  54.         exit $?
  55.     else
  56.         echo -n "Stressing f_which... "
  57.         n=0
  58.         start_epoch=$( date +%s )
  59.         while [ $n -lt $STRESS ]; do
  60.             f_which "$1" > /dev/null
  61.             n=$(( $n + 1 ))
  62.         done
  63.         end_epoch=$( date +%s )
  64.         echo "$(( $end_epoch - $start_epoch )) seconds ($STRESS runs)"
  65.  
  66.         echo -n "Stressing which... "
  67.         n=0
  68.         start_epoch=$( date +%s )
  69.         while [ $n -lt $STRESS ]; do
  70.             which "$1" > /dev/null
  71.             n=$(( $n + 1 ))
  72.         done
  73.         end_epoch=$( date +%s )
  74.         echo "$(( $end_epoch - $start_epoch )) seconds ($STRESS runs)"
  75.     fi
  76. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement