Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C programming tricks

Name: Anonymous 2007-09-15 22:06 ID:WCtjqT0N

While programming optimization that makes ones' code completely unreadable is often a bad thing, there are places for it, like that one inner loop of your code that takes up 98% of the program's running time.

What are you tricks for improving performance in C, other than the obvious inline assembly or the like?

Name: Anonymous 2007-09-16 15:23 ID:xXOet/pd

>>44
integer division is pretty damn fast.
rand()&1 is a lot less random than rand()/(INT_MAX/2).

>>43
$ cat test1.c
#include <stdio.h>
#include <stdlib.h>

int main(){
 for(int i=0;++i<1000000;printf("%d\n",rand()%2));
 return 0;
}
$ cat test2.c
#include <stdio.h>
#include <stdlib.h>

int main(){
 for(int i=0;++i<1000000;printf("%d\n",rand()&1));
 return 0;
}
$ cat test3.c
$ cat test3.c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(){
 for(int i=0;++i<1000000;printf("%d\n",rand()/(INT_MAX/2)));
 return 0;
}
$ gcc -std=c99 test1.c -o test1
$ gcc -std=c99 test2.c -o test2
$ gcc -O2 -std=c99 test3.c -o test3
$ time -h ./test1 > /dev/null
        0.73s real              0.63s user              0.00s sys
$ time -h ./test2 > /dev/null
        0.72s real              0.64s user              0.00s sys
$ time -h ./test3 > /dev/null
        0.72s real              0.63s user              0.00s sys

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List