Skip to content

Instantly share code, notes, and snippets.

@inaz2
Created January 24, 2016 14:41
Show Gist options
  • Save inaz2/0b49108834918b5e8bfb to your computer and use it in GitHub Desktop.
Save inaz2/0b49108834918b5e8bfb to your computer and use it in GitHub Desktop.
time for 2^32 loops in C, golang, Python
$ cat loop.c
int main()
{
long i;
for (i=0; i<(1L<<32); i++) {
}
return 0;
}
$ cat loop.go
package main
func main() {
for i := 0; i < (1<<32); i++ {
}
}
$ cat loop.py
i = 0
while i < (1<<32):
i += 1
$ gcc loop.c -o loop-c
$ objdump -d loop-c | awk '/<main>:/,/^$/'
00000000004004ed <main>:
4004ed: 55 push rbp
4004ee: 48 89 e5 mov rbp,rsp
4004f1: 48 c7 45 f8 00 00 00 mov QWORD PTR [rbp-0x8],0x0
4004f8: 00
4004f9: eb 05 jmp 400500 <main+0x13>
4004fb: 48 83 45 f8 01 add QWORD PTR [rbp-0x8],0x1
400500: b8 ff ff ff ff mov eax,0xffffffff
400505: 48 39 45 f8 cmp QWORD PTR [rbp-0x8],rax
400509: 7e f0 jle 4004fb <main+0xe>
40050b: b8 00 00 00 00 mov eax,0x0
400510: 5d pop rbp
400511: c3 ret
400512: 66 2e 0f 1f 84 00 00 nop WORD PTR cs:[rax+rax*1+0x0]
400519: 00 00 00
40051c: 0f 1f 40 00 nop DWORD PTR [rax+0x0]
$ gcc -O1 loop.c -o loop-c1
$ objdump -d loop-c1 | awk '/<main>:/,/^$/'
00000000004004ed <main>:
4004ed: 48 b8 00 00 00 00 01 movabs rax,0x100000000
4004f4: 00 00 00
4004f7: 48 83 e8 01 sub rax,0x1
4004fb: 75 fa jne 4004f7 <main+0xa>
4004fd: b8 00 00 00 00 mov eax,0x0
400502: c3 ret
400503: 66 2e 0f 1f 84 00 00 nop WORD PTR cs:[rax+rax*1+0x0]
40050a: 00 00 00
40050d: 0f 1f 00 nop DWORD PTR [rax]
$ gcc -O2 loop.c -o loop-c2
$ objdump -d loop-c2 | awk '/<main>:/,/^$/'
0000000000400400 <main>:
400400: 31 c0 xor eax,eax
400402: c3 ret
$ go build -o loop-go loop.go
$ objdump -d loop-go | awk '/<main.main>:/,/^$/'
0000000000400c00 <main.main>:
400c00: 48 31 c0 xor rax,rax
400c03: 48 bd 00 00 00 00 01 movabs rbp,0x100000000
400c0a: 00 00 00
400c0d: 48 39 e8 cmp rax,rbp
400c10: 7d 12 jge 400c24 <main.main+0x24>
400c12: 48 ff c0 inc rax
400c15: 48 bd 00 00 00 00 01 movabs rbp,0x100000000
400c1c: 00 00 00
400c1f: 48 39 e8 cmp rax,rbp
400c22: 7c ee jl 400c12 <main.main+0x12>
400c24: c3 ret
...
$ time ./loop-c
real 0m10.693s
user 0m10.676s
sys 0m0.004s
$ time ./loop-c1
real 0m1.855s
user 0m1.852s
sys 0m0.000s
$ time ./loop-go
real 0m2.178s
user 0m2.172s
sys 0m0.036s
$ time python loop.py
real 5m2.412s
user 5m2.188s
sys 0m0.016s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment