I have a problem with time measuring that’s really bothering me. I am executing something like the following code (in C#) :
Stopwatch sw = Stopwatch.StartNew();
Foo(args);
sw.Stop();
//log time
public void Foo(var args)
{
Stopwatch sw = Stopwatch.StartNew();
//do stuff
sw.Stop();
//log time
}
And the result is a big difference between both times, my code gives me : 15535 ms from inside the function, and 15668 ms from the outside… 133ms seems a lot to me for a function call (even with the 10 params I am giving to mine), or to incriminate Stopwatch precision (which is supposed to be super precise).
How would you explain this difference in times ?
note 1 : Same thing happens on several successive calls : I am getting 133, 81, 72, 75, 75 milliseconds difference for 5 calls
note 2 : the actual parameters of my function are :
- 6 class objects
- one array of struct (the array is passed as reference, right ?)
- 2 ref int
- 1 out byte[]
- 1 out class
- 1 out struct of small size (< 25 bytes)
Update :
In Release, the difference for the first call is even bigger (is JIT compilation more expensive in release, which could explain that ?), and the next steps have the same overhead (~75 ms)
I tried to initialize stopwatches outside, pass one as parameter and log outside of the function, the difference is still there.
I also forgot that I am giving some properties as parameters that have to be constructed the first time, so the 50ms difference for the first call might be explained by properties initialization and JIT compilation.
My bad, It was a property calling a property doing some disk read access. I thought it was a simple member and didn’t go deep enough. I took the calls out of the function call and times are now almost the same (0-1 ms, I guess it’s the logging)
The moral is : properties should not have side effects. If you make a property that is not doing something obvious, code a function instead, or at least warn the next developer about what you are doing in the documentation of the property !
And the moral of the moral is : If something looks suspicious, always look at the call tree to the deepest level !