C# Functions faster in time measurement after pre-calling it? -


i`m trying find out why functions seem run faster after called once before measuring time.

here sample of measurement code:

            float x = 0;         fastmath.fireup(); // nothing in sample         stopwatch watch = new stopwatch();         watch.start();         (int = 0; < 5; i++)         {             x = fastmath.fastsin(i);         }         watch.stop();         console.writeline("time : " + watch.elapsed ); 

and here can see called function:

        public static float fastsin(float val)     {         int index = 360 - ((int)val % 360);         if(index == 360)         {             return 0;         }         return -trigonometric_lookuptable[index];     } 

so thing is, measurement shows following output:

time : 00:00:00.0001196

lets fill "fireup" function with:

float x = fastsin(123); 

now measured time decreased significantly:

00:00:00.0000015

but still, "fastcos", wasn`t called in fireup function, still takes longer time.

two other points should mention:

  • if dont call "fireup" function, time increases again:

    time : 00:00:00.0002796

  • if fill "fireup" function with:

    float x = fastsin(123); x = fastcos(123);

    it runs fine both functions in future measurement. takes time : 00:00:00.0000019 each function.

why happening?

when compiling managed code, compiler translates source code microsoft intermediate language (msil), cpu-independent set of instructions can efficiently converted native code.

on runtime msil code compiled (by jit) binary platform dependent code. clr compiles used paerts of code compile fastsin method before calls first time.

the runtime supplies mode of compilation called install-time code generation. install-time code generation mode converts msil native code regular jit compiler does, converts larger units of code @ time, storing resulting native code use when assembly subsequently loaded , run.

you can read more msil , compiling msil native code.


Comments