??? 06/13/07 15:20 Modified: 06/13/07 17:11 Read: times |
#140680 - Post Mortem #1 Responding to: ???'s previous message |
Well, well. Since we've been stalled for a day or so now with Chris's 34-byte program as the shortest one, maybe it would be interesting to continue what Michael started and see how the code generated by the compiler related to the source code. Like Michael, I used the Keil compiler with its optimization level set at 8.
Here are the programs: 1. c=c/2&85|c*2&170;c=c/4&51|c*4&204;RT c>>4|c<<4; // (47 bytes) 2. UC r,i=8;WH(i--){r>>=1;r|=c&128;c*=2;}RT r; // (43 bytes) 3. UC r,i=8;WH(i--){r*=2;r|=c&1;c/=2;}RT r; // (40 bytes) 4. UC r,i=8;WH(i--){r=r*2|c&1;c/=2;}RT r; // (38 bytes) 5. UC r,i=8;WH(i--)r=r*2|c&1,c/=2;RT r; // (36 bytes) 6. UC r,i=1;WH(r+=c&i?r++:r,i+=i);RT r; // (36 bytes) 7. IN r=1;WH(r<256)r=r*2|c&1,c/=2;RT r; // (36 bytes) 8. UC r,i=1;WH(r+=r+c/i%2,i+=i);RT r; // (34 bytes)And here is a summary of the results Program Length of generated code 1 38 2 26 3 26 4 26 5 26 6 25 7 35 8 22As you might expect, the shorter C programs generally produced less generated code. Program #7 is a glaring exception. Its problem is that it uses a 16-bit variable, which is obviously an expensive proposition on an 8-bit machine. Here's the generated code for #8: ; UC r,i=1;WH(r+=r+c/i%2,i+=i);RT r; ;---- Variable 'c' assigned to Register 'R7' ---- ;---- Variable 'i' assigned to Register 'R6' ---- 0000 7E01 MOV R6,#01H 0002 ?C0028: 0002 EF MOV A,R7 0003 8EF0 MOV B,R6 0005 84 DIV AB 0006 5401 ANL A,#01H 0008 2500 R ADD A,r 000A 2500 R ADD A,r 000C F500 R MOV r,A 000E EE MOV A,R6 000F 2E ADD A,R6 0010 FE MOV R6,A 0011 70EF JNZ ?C0028 0013 AF00 R MOV R7,r 0015 22 RETA (nearly?) optimized (for size) ASM solution is about half as big. 0047 Flip5: 0047 C8 xch a,r0 0048 7480 mov a,#80h ; Done when this bit pops out 004A Floop5: 004A C8 xch a,r0 ; Shift MSB out of source byte ... 004B 33 rlc a 004C C8 xch a,r0 ; ... and into destination 004D 13 rrc a 004E 50FA jnc Floop5 ; Done when initial bit pops out 0050 22 retThat 2-to-1 size reduction by going to ASM is pretty impressive, but not something you would expect to see with every problem. For example, the code generated by a compiler for the straightforward initialization of a bunch of 8051 peripherals, where all you're doing is setting a bunch of constant values into a bunch of SFRs, would probably be identical to what an ASM programmer would write. -- Russ |