Timing of functions in C#

  • Thread starter Thread starter DrOrbit
  • Start date Start date
D

DrOrbit

I am working on a rather large program that hits several methods
multiple times. In looking for ways to speed it up, I have discovered
something odd. The first time I call a method, it's about 30 times
slower than any subsequent call. This is true for all the methods that
I have tested. For example, the first call might take 30 milliseconds
whereas all subsequent calls take less than 1 ms. I would like to
understand why this is happening.

An example method looks like this:

public void computeVecP () // Escobal 5.3
{
VecP.X = (SatObs.Sat.KepElements.CosArgPerigee *
SatObs.Sat.KepElements.CosLongAsc) -
(SatObs.Sat.KepElements.SinArgPerigee *
SatObs.Sat.KepElements.SinLongAsc * SatObs.Sat.KepElements.CosInc);

VecP.Y = (SatObs.Sat.KepElements.CosArgPerigee *
SatObs.Sat.KepElements.SinLongAsc) +
(SatObs.Sat.KepElements.SinArgPerigee *
SatObs.Sat.KepElements.CosLongAsc * SatObs.Sat.KepElements.CosInc);

VecP.Z = SatObs.Sat.KepElements.SinArgPerigee *
SatObs.Sat.KepElements.SinInc;
}

Each term is "a property of a property of a property" and all values
have been pre-computed. In other words,
"SatObs.Sat.KepElements.CosArgPerigee" is declared as
public double CosArgPerigee{get{return cosArgPerigee;}
set{cosArgPerigee=value;}}

If I substitute simple variables (i.e. "X" for
"SatObs.Sat.KepElements.CosArgPerigee") then the time difference
disappears. Therefore I conclude that C# is spending a long time
locating the first property look-up but somehow doesn't need to do it
again for subsequent calls. I hope that I'm making sense here. Is
there a better or more complete explanation?
 
The first time a method is called it is JIT'd. The Just In Time compiler
will compile the IDL, then will use the compiled version for subsequent
calls.
 
Floyd said:
The first time a method is called it is JIT'd. The Just In Time compiler
will compile the IDL, then will use the compiled version for subsequent
calls.

I think there was some tool that can be used to pre-compile the whole
program so it doesn't need to be just in time compiled. If the delay at the
first call is causing you problems you could try that. I can't remember
what the tool was called - try google!

Max
 
The longer time to execute is not a problem, but I was curious about
what was going on behind the scenes. Floyd's explanation makes sense.
I appreciate the responses.
 
Back
Top