Is there a way to count the number of IL instructions executed?

╄→гoц情女王★ 提交于 2019-11-30 22:55:27

I don't think it's possible to do what you want. This is because the IL is only used during JIT (Just-In-Time) compilation. By the time the method is running the IL has been translated into native machine code. So, while it might be possible to count the number of IL instructions in a given method/type/assembly statically, there's no concept of this at runtime.

You haven't stated your intention in knowing the number of IL instructions that would be interpreted. Given that there's only a loose correlation between the IL count of a method body and the actual number of machine code instructions, I fail to see what knowing this number would achieve (other than satisfying your curiosity).

Well, it won't be easy. I think you could instrument your assembly post-compile with performance counter code that executed after blocks of IL. For example, if you had a section of a method that loaded an int onto the stack then executed a static method using that int under optimized code, you could record a count of 2 for the int load and call.

Even using existing IL/managed assembly reading/writing projects, this would be a pretty daunting task to pull off.

Of course, some instructions that your counter recorded might get optimized away during just-in-time compiling to x86/ia64/x64, but that is a risk you'd have to take to try to profile based on an abstract lanaguage like IL.

You could use ICorDebug which has a managed interface. Chuck a break point at the beginning of the method and programmaticly step through the code till it leaves the method.

However, I am not sure how useful the metric will be, people tend to use time for this kind of stuff. Some IL instructions are more expensive than others.

I use the Code Metrics add in to Reflector

The CodeMetrics add-in analyses and computes several code quality metrics on your assemblies. This add-in uses Reflector to compute classic metrics such as cyclomatic complexity or more straightforward ones such as the number of local variables in a method. All results can be saved to a file.

Install the plugin. Select an assembly and load method metrics. It will show you a grid with CodeSize, CyclomaticComplexity, # of Instruction, etc.

I know you don't want the static count. However, the static IL count per arc, plus the number of times the arc was executed together give you the IL count. You'd need to instrument each arc for this, which requires inserting a counter.

(An arc is a sequence of instructions which you can't jump in or out. If you execute the first instruction, you'll always execute the last, etc.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!