i`m just trying to find out why functions seem to run faster after they were called once before measuring the time.
Here is a sample of my measurement code:
float X = 0;
FastMath.FireUp(); // Does nothing in this sample
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 5; i++)
{
X = FastMath.FastSin(i);
}
watch.Stop();
Console.WriteLine("TIME : " + watch.Elapsed );
And here you can see my called function:
public static float FastSin(float val)
{
int index = 360 - ((int)val % 360);
if(index == 360)
{
return 0;
}
return -TRIGONOMETRIC_LOOKUPTABLE[index];
}
So the thing is, that my measurement shows following output:
TIME : 00:00:00.0001196
Lets fill the "FireUp" function with:
float x = FastSin(123);
Now the measured time decreased significantly:
00:00:00.0000015
But still, "FastCos", which wasn`t called in the FireUp function, still takes the longer time.
Two other points which i should mention:
TIME : 00:00:00.0002796
If I fill my "FireUp" function with:
float x = FastSin(123); x = FastCos(123);
It just runs fine for both functions in the future measurement. Now it takes TIME : 00:00:00.0000019 for each function.
Why is that happening?
When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code.
On the runtime MSIL code compiled (by JIT) to the binary platform dependent code. CLR compiles just used paerts of code then it will compile FastSin
method just before it calls first time.
The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and run.
You can read more about MSIL and Compiling MSIL to Native Code.