views:

34

answers:

1

Does the objective-c compiler in Xcode know better, or is it faster if I use bit shift for multiplications and divisions by powers of 2?

NSInteger parentIndex = index >> 1; // integer division by 2
+1  A: 

Isn't this a bit 1980's? Don't processors run these instructions in the same time these days? I remember back in my 68000 days when a div was 100+ cycles and a shift only 3 or 4... not sure this is the case any more as processors have moved on.

Why don't you get the compiler to generate the assembler file and have a look what it's generating and run some benchmarks.

I found this on the web which may help you... although it's for 'C' I think most of the options will be the same.

Q: How can I peek at the assembly code generated by GCC?

Q: How can I create a file where I can see the C code and its assembly
   translation together?

A: Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:

gcc -O2 -S -c foo.c

will leave the generated assembly code on the file foo.s.

If you want to see the C code together with the assembly it was converted to, use a command line like this:

gcc -c -g -Wa,-a,-ad [other GCC options] foo.c > foo.lst

which will output the combined C/assembly listing to the file foo.lst.

If you need to both get the assembly code and to compile/link the program, you can either give the -save-temps option to GCC (which will leave all the temporary files including the .s file in the current directory), or use the -Wa,aln=foo.s option which instructs the assembler to output the assembly translation of the C code (together with the hex machine code and some additional info) to the file named after the =.

Tony Lambert
I can actually generate the assembly code from the context menu. I have no clue what I'm looking at, but it seems asr (arithmetic shift right) is present in both situations. If I divide by 3, there's an smul instruction before asr.
hyn
doen't that answer your question then.... If you call this millions of times and time the two different bits of code then you can see for sure. Sounds like it optimises it to me.
Tony Lambert