Question

Out of curiosity I'm trying to find out how many operations it takes for a certain method to complete.

More clear and concise than before:

doThis();
doAswell();
doToo();

I want to know how many arithmetic operations, that means actual processor actions it takes to get from calling doAswell(); to completing it.

private void doAswell()
{
    int counter = 0;
    while(counter < 1000)
        counter++;
}

This for example taking about 2000 ALU-steps (1000 compares + 1000 increments) + some overhead for allocation of counter.
Obviously I am looking to do this on more complex operations(constructors, etc.), which actually take multiple ALU-steps for one operation.

My question:
Can I at all count the operations performed between two points in a program?
And if so: How?

Was it helpful?

Solution

Interpretation of the question: how many instructions are executed to perform an operation.

If correct:

C# is compiled to MSIL. You can inspect the generated MSIL using ILSpy. This can give a rough indication.

Generated MSIL is however not executed directly but passed to the JIT that converts the MSIL to instruction understood by the ALU. I don't know if there is way to see the instructions after the JIT. Never had the need for it.

Other option is to use NGEN on the assembly. NGEN creates a binary with native instructions for the target platform. You can use a disassembler on the output.

But my guess is that the curiosity is there from a performance perspective.

Influencing the JIT on codegeneration is not trivial (if doable).

Use a profiler to find the bottleneck and alter the C# code to improve performance is the most trivial and maintainanble way imho.

If there is no way to get the needed performance try to recode the needed parts in C(++).

C# is a high-level language and the level of abstraction adds some level of overhead. The JIT is however quite smart, outperforming it with handcrafted code is a challenge.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top