除算を早くする

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int cntr = 0;
    cntr = (cntr +1) % 32;
    return cntr;
}

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int cntr = 0;
    cntr = (cntr +1) & 0x1f;
    return cntr;
}

と書く。
アセンブルして比較。

before

	.file	"mod_optimize.c"
	.text
.globl main
	.type	main, @function
main:
	leal	4(%esp), %ecx
	andl	$-16, %esp
	pushl	-4(%ecx)
	pushl	%ebp
	movl	%esp, %ebp
	pushl	%ebx
	pushl	%ecx
	subl	$20, %esp
	movl	$0, -12(%ebp)
	movl	-12(%ebp), %ecx
	addl	$1, %ecx
	movl	$1717986919, -28(%ebp)
	movl	-28(%ebp), %eax
	imull	%ecx
	sarl	%edx
	movl	%ecx, %eax
	sarl	$31, %eax
	movl	%edx, %ebx
	subl	%eax, %ebx
	movl	%ebx, %eax
	movl	%eax, -12(%ebp)
	movl	-12(%ebp), %edx
	movl	%edx, %eax
	sall	$2, %eax
	addl	%edx, %eax
	movl	%ecx, %edx
	subl	%eax, %edx
	movl	%edx, %eax
	movl	%eax, -12(%ebp)
	movl	-12(%ebp), %eax
	addl	$20, %esp
	popl	%ecx
	popl	%ebx
	popl	%ebp
	leal	-4(%ecx), %esp
	ret
	.size	main, .-main
	.ident	"GCC: (GNU) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)"
	.section	.note.GNU-stack,"",@progbits

after

	.file	"mod_optimize_and.c"
	.text
.globl main
	.type	main, @function
main:
	leal	4(%esp), %ecx
	andl	$-16, %esp
	pushl	-4(%ecx)
	pushl	%ebp
	movl	%esp, %ebp
	pushl	%ecx
	subl	$16, %esp
	movl	$0, -8(%ebp)
	movl	-8(%ebp), %eax
	addl	$1, %eax
	andl	$31, %eax
	movl	%eax, -8(%ebp)
	movl	-8(%ebp), %eax
	addl	$16, %esp
	popl	%ecx
	popl	%ebp
	leal	-4(%ecx), %esp
	ret
	.size	main, .-main
	.ident	"GCC: (GNU) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)"
	.section	.note.GNU-stack,"",@progbits

一行変えただけなのに。
すっすげぇぜ。(ごくり)
 

参考

Write Great Code〈Vol.1〉ハードウェアを知り、ソフトウェアを書く

Write Great Code〈Vol.1〉ハードウェアを知り、ソフトウェアを書く