while(1){LOVE++;} を最適化

while(1){LOVE++;}を最適化 (duost) に書かれてた内容。何か話題になってたらしいけど…。


元となるソース。

int main() {
    int LOVE = 0;
    while(1){LOVE++;}
}


まずは、最適化なし `gcc -O0 -S lovepp.c`

	.file	"lovepp.c"
	.globl	__stack_smash_handler
	.text
	.globl	main
	.type	main, @function
main:
	pushl	%ebp
	movl	%esp, %ebp
	subl	$40, %esp
	andl	$-16, %esp
	movl	$0, %eax
	subl	%eax, %esp
	movl	__guard, %eax
	movl	%eax, -24(%ebp)
	movl	$0, -28(%ebp)
.L2:
	leal	-28(%ebp), %eax
	incl	(%eax)
	jmp	.L2
	.size	main, .-main


で、最適化あり `gcc -O1 -S lovepp.c`

	.file	"lovepp.c"
	.globl	__stack_smash_handler
	.text
	.globl	main
	.type	main, @function
main:
	pushl	%ebp
	movl	%esp, %ebp
	subl	$24, %esp
	andl	$-16, %esp
	movl	__guard, %eax
	movl	%eax, -24(%ebp)
.L5:
	jmp	.L5
	.size	main, .-main


って事で、うつろいやすい(volatile) LOVE って宣言してから最適化ありで

	.file	"lovepp.c"
	.globl	__stack_smash_handler
	.text
	.globl	main
	.type	main, @function
main:
	pushl	%ebp
	movl	%esp, %ebp
	subl	$40, %esp
	andl	$-16, %esp
	movl	__guard, %eax
	movl	%eax, -24(%ebp)
	movl	$0, -28(%ebp)
.L5:
	movl	-28(%ebp), %eax
	incl	%eax
	movl	%eax, -28(%ebp)
	jmp	.L5
	.size	main, .-main

結果、うつろいやすくないと消されてしまうと(ぉぃ。

ってか、printfなりでアウトプットすれば…。ただ増やした(気になってる)だけじゃなくて、それを表に出してあげなきゃダメと…。


あっ、動かした環境

$ uname -a
OpenBSD openbsd.example.com 4.7 GENERIC#558 i386
$ gcc --version
gcc (GCC) 3.3.5 (propolice)
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

※ホスト名だけ改変