I needed to check performance of some .NET API, and I came up with this code.
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++) {
int res = (int) SOME .NET FUNCTION TO RUN;
}
sw.Stop();
double time = sw.Elapsed.TotalMilliseconds;
On my second thought, I was afraid that the compiler optimizes out all the operation as the res is not used any where. And I modified the code as follows.
Stopwatch sw = Stopwatch.StartNew();
long sumIt = 0;
for (int i = 0; i < 1000; i++) {
int res = (int) SOME .NET FUNCTION TO RUN;
sumIt += res;
}
sw.Stop();
double time = sw.Elapsed.TotalMilliseconds;
value = (int) sumIt / 1000;
Interestingly, it doesn’t seem that the compiler doesn’t optimize out the operation with my first example. I tested with csc (Visual Studio), and mono.
Here comes my questions.
- Is it safe to make a benchmark as my first example?
- Isn’t C# compiler smart enough to understand that some of the code can be optimized out? Or, is there any compiler parameter for that?
ADDED
The SOME FUNCTION TO RUN is actually SOME .NET FUNCTION TO RUN, and I modified the OP.
And based on the answers, it looks like that the C# compiler cannot(or doesn’t) optimize the operation as the .NET FUNCTION TO RUN might have the side effect.
Compiler (JIT) may optimize whole function call out if it finds out that it has no side effects. It likely need to be able to inline function to detect that.
I tried small function that only acts on input arguments and see it is optimized out by checking resulting assembly (make sure to try Release build with “Suppres optimization on module load” unchecked).
Disassembly: