[Everything: this answer was written with the assumption that the calls to rand () were part of the problem. I suggest an improvement below in this assumption. The OP fears that he only used Rand to tell us the ranges (and presumably distributions) of the x and y values. It is unclear whether it mattered to u. In any case, enjoy my improved answer to a problem that he really had no idea].
I think you'd better rewrite this as:
int u, x, y; x = rand() % 100 - 50; y = rand() % 100 - 50; if ( y > x) u = 5; else if (-y > x) u = 4; else u = rand() % 4;
This calls the last rand only 1/4 as often as the OP source code. Since I assume that rand (and division) is much more expensive than comparison and branch, this will be significant savings.
If your rand generator produces a lot of really random bits (e.g. 16) on each call, as you would expect, you can only call it once (I assumed rand is more expensive than divide, YMMV):
int u, x, y, t; t = rand() ; u = t % 4; t = t >> 2; x = t % 100 - 50; y = ( t / 100 ) %100 - 50; if ( y > x) u = 5; else if (-y > x) u = 4;
I think the rand function in the MS C library is not good enough for this if you want really random values. I had to code my own; in any case, it turned out to be faster.
You can also get rid of the gap using multiplication by the inverse (untested):
int u, x, y; unsigned int t; unsigned long t2; t = rand() ; u = t % 4; {
If your compiler will not create the βcorrectβ instructions, just write the assembly code for this.
source share