Re: absolute function
- Posted by mattlewis (admin) Mar 24, 2011
- 3561 views
bill said...
function abs(integer x) return and_bits(-(x<0), -x) + and_bits(-(x>0), x) end function
for what it is worth.
Pretty clever. I haven't tested, but for integers, a simple if statement should be faster:
function simple_abs( integer x ) if x >= 0 then return x else return -x end if end function
If you look at the IL code for the two of them:
SubProgram [/home/matt/eu/test/bill.ex-abs:00146] [x:148] STACK SPACE: 9 Required: 9 [/home/matt/eu/test/bill.ex:1] (1) 1: 096 148 # INTEGER_CHECK: [x:148] [/home/matt/eu/test/bill.ex:2] (2) 3: 001 148 143 149 # LESS: [x:148], [LIT 0:143] => [_temp_:149] 7: 012 149 150 # UMINUS: [_temp_:149] => [_temp_:150] 10: 012 148 151 # UMINUS: [x:148] => [_temp_:151] 13: 056 150 151 152 # AND_BITS: [_temp_:150], [_temp_:151] => [_temp_:152] 17: 006 148 143 153 # GREATER: [x:148], [LIT 0:143] => [_temp_:153] 21: 012 153 154 # UMINUS: [_temp_:153] => [_temp_:154] 24: 056 154 148 155 # AND_BITS: [_temp_:154], [x:148] => [_temp_:155] 28: 011 152 155 156 # PLUS: [_temp_:152], [_temp_:155] => [_temp_:156] 32: 208 150 # DEREF_TEMP: [_temp_:150] 34: 208 151 # DEREF_TEMP: [_temp_:151] 36: 208 152 # DEREF_TEMP: [_temp_:152] 38: 208 154 # DEREF_TEMP: [_temp_:154] 40: 208 155 # DEREF_TEMP: [_temp_:155] 42: 028 146 147 156 # RETURNF: [_temp_:156] block[147] 46: 043 # BADRETURNF: End SubProgram [abs:00146] SubProgram [/home/matt/eu/test/bill.ex-simple_abs:00157] [x:159] STACK SPACE: 3 Required: 3 [/home/matt/eu/test/bill.ex:5] (5) 1: 096 159 # INTEGER_CHECK: [x:159] [/home/matt/eu/test/bill.ex:6] (6) 3: 120 159 143 13 # GREATEREQ_IFW [x:159] > [LIT 0:143] goto 0007 else goto 0013 [/home/matt/eu/test/bill.ex:7] (7) 7: 028 157 158 159 # RETURNF: [x:159] block[158] [/home/matt/eu/test/bill.ex:8] (8) 11: 023 20 # ELSE goto 0020 [/home/matt/eu/test/bill.ex:9] (9) 13: 012 159 163 # UMINUS: [x:159] => [_temp_:163] 16: 028 157 158 163 # RETURNF: [_temp_:163] block[158] 20: 043 # BADRETURNF: End SubProgram [simple_abs:00157]
There are lots of operations created, and several temps.
Matt