Truc et astuces: calculs entiers en bash

felix <[email protected]>
Newsgroups gmane.org.user-groups.gull.general
Message-ID <[email protected]>
Bonjour,

En bash, on peut faire un calcul entier suivant la syntaxe:

   val=$(( 3 * 7 * 2 ))

comme:

   declare -i val
   val=' 3 * 7 * 2 '

dans les 2 cas, la variable 'val' contiendra '42'.

Par contre, il y a une différence de performance:

  https://f-hauri.ch/vrac/bashInteger.sh.txt

Voici le temps qui a fallu pour assigner 491'022x '11 ** 12 / 3 % 470' à une
variable, compte tenus que cette variable soit définie comme chaine de
caractère ou comme nombre entier (declare -i).

  String var = '...'      :  618.378ms  -> '11 ** 12 / 3 % 470'
  Integer var = '...'     :  832.276ms  -> '80'
  String var = $(( ... )) : 1123.090ms  -> '80'
  Integer var = $(( ... )): 1124.578ms  -> '80'

Assigner
 - une chaine à une variable chaine est rapide, bon.
 - une chaine à une variable de type entier -> calcul bash rapide.
 - un entier calculé à une variable chaine -> calcul bash  moins rapide.
 - un entier à une variable de type entier, un tout petit poil moins rapide

Donc, quand le calcul est fait avec $((...)), c'est presque 2x moins rapide
que si bash fait l'opération en assignant à une variable entière.

-- 
 Félix Hauri  -  <[email protected]>  -  http://www.f-hauri.ch
_______________________________________________
gull mailing list
[email protected]
https://forum.linux-gull.ch/mailman/listinfo/gull
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.