Can I read the CPU performance counters from a user-mode program in Windows?

对着背影说爱祢 提交于 2019-12-03 09:40:52

问题


I would like to program and read the hardware performance counters offered on all recent x86 hardware.

On Linux there are the various perf_events systems to do this (and the perf utility to do it from outside an unmodified program).

Is there any such built-in facility in Windows? If no built-in facility exists, the second best would be another approach perhaps using third-party code, but that doesn't require me to get a driver signed.


回答1:


Short answer

No, there's no built-in facility in Windows. Also the linux perf command doesn't work on the Linux Subsystem for Windows 10.

Long answer

To get access to those counters, you'll need a combination of these instructions:

  • rdpmc __readpmc (see related answer)
  • rdmsr __readmsr
  • wrmsr __writemsr

Unfortunately these instructions can only be called from kernel mode, so you'll need to interface with a driver. While writing the driver code itself is easy, getting the driver signed is not that easy (especially as you mentioned you want to do this as an individual).

That's why I advise you to look into existing projects like Open Hardware Monitor and the pcm project by Intel.

Open Hardware Monitor

This open-source project is written in C# and includes binaries and C source-code of a WinRing0.sys (32-bit) / WinRing0x64.sys (64-bit) driver developed by OpenLibSys.org. If you want to use this driver in your project, you only need to include their copyright notice.

PCM

This open-source project is written in C++ and also contains source for a similar driver (see WinMSRDriver directory), but you have to build it yourself so you'll turn into the signing problem again.

Anyway, wanted to mention this project because it probably contains a lot of code which might be of your interest.

User-Mode access

Now, once you have that driver loaded (Open Hardware Monitor extracts and loads the driver automatically on start of the application which is pretty neat), you can start calling those driver IOCTL's by using the Windows API functions CreateFile / DeviceIoControl and of course CloseHandle from your user-mode application.



来源:https://stackoverflow.com/questions/45428588/can-i-read-the-cpu-performance-counters-from-a-user-mode-program-in-windows

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