c# - 获取执行指令数的方法是什么?

标签 c# .net performance profiler

我读过

One way to understand how the processor used its time is to look at the hardware counters. To help with performance tuning, modern processors track various counters as they execute code: the number of instructions executed, the number of various types of memory accesses, the number of branches encountered, and so forth. To read the counters, you’ll need a tool such as the profiler in Visual Studio 2010 Premium or Ultimate, AMD Code Analyst or Intel VTune.

那么通过像使用 PerformanceCounter 这样的编码来实现并执行这些指令数的方法是什么?

有什么方法可以计算 DotTrace、Ants、VS profiler 等指令的命中率吗?

最佳答案

对于VS Profiler :

To view a list of a list of all CPU counters that are supported on the current platform

In Performance Explorer, right-click the performance session and then click Properties.

Do one of the following:

  1. Click Sampling, and then select Performance counter from the Sample event list. The CPU counters are listed in Available performance counters. Note Click Cancel to return to the previous sampling configuration.

-or-

  1. Select CPU Counters, and then select Collect CPU Counters. The CPU counters are listed in Available counters. Note Click Cancel to return to the previous counter collection configuration.

您无法从您的程序访问完整的 CPU 计数器,因为:https://stackoverflow.com/a/8800266/613130

You can use RDPMC instruction or __readpmc MSVC compiler intrinsic, which is the same thing.

However, Windows prohibits user-mode applications to execute this instruction by setting CR4.PCE to 0. Presumably, this is done because the meaning of each counter is determined by MSR registers, which are only accessible in kernel mode. In other words, unless you're a kernel-mode module (e.g. a device driver), you are going to get "privileged instruction" trap if you attempt to execute this instruction.

(RDPMC是返回CPU计数器的指令)

我要补充一点,通常执行的指令数是毫无用处的。重要的是用于执行某些代码的 CPU 时间。每条指令都有不同的 CPU 时间,因此即使知道它们的数量,您也不会知道使用的 CPU 周期数/时间。

如果你想知道某些指令使用的CPU周期,那么你可以使用ASM指令RDTSC/RDTSCP。在 C# 中使用它非常复杂且非常耗时(因此使用它的速度很慢,通常会影响您尝试进行的测量)。如果你有兴趣,我前几天写了一个回复:https://stackoverflow.com/a/29646856/613130

关于c# - 获取执行指令数的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29792471/

相关文章:

c# - MVC4 : Compilation Error The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced

c# - 使用 Linq 和 XDocument,我可以获取父标签下的所有子元素吗?

c - 在传递给函数和访问存储在 C 中的值时有效地使用结构的结构

r - 如何加入具有多列和多个值的 data.table

C# 手动排序列表中的父/子树元素

c# - 从名称中获取对象

c# - 最适合覆盖 mvc 基本 Controller 以设置文化的方法

c# - 作为管道的 RX IObservable

c# - 是否在垃圾回收期间调用了所有终结器?

Java 编码器性能