Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of CPU cycles used by a process

I have a need to get the number of CPU cycles used by a specific process using C# (or VB.Net). This information is available in the Process properties popup within Sysinternal's Process Explorer. For instance, the browser that I'm using the post this message has currently used 18,521,360,165 cyles (give or take a few hundred million). Does anyone know how to get this information from a .Net app? I know how to get the CPU usage (percentage), but this isn't what I'm looking for. I need a way to compare CPU usage between two different processes running at different times.

Thank you, Matt

Update:
Why do I need this? I'm the leader of the local .Net user group and we're running a code challenge where developers submit code to solve a problem. I need a way to measure the performance of one entry against another. Currently I'm using a timer to measure performance. The server is 100% dedicated to this, but that doesn't guarantee that something else might be happening at the same time. Obviously, this is frought with all kinds of potential issues, but generally speaking, it's fairly accurate. Measuring the number of CPU cycles used would be an almost fool proof way to measure how well someone's entry performs against another. I'm certain that someone can shoot holes all over this - no need to try at this point. ;-) I hope that helps explain the reason behind my question and why a timer is insufficient for solving my problem.

like image 335
Matt Ruwe Avatar asked Jun 29 '11 20:06

Matt Ruwe


2 Answers

Process Explorer calls QueryProcessCycleTime to get that information. You will probably have to use P/Invoke to call it. I would expect its P/Invoke signature to look like:

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool QueryProcessCycleTime(IntPtr ProcessHandle, out ulong CycleTime);
like image 81
Gabe Avatar answered Sep 27 '22 01:09

Gabe


You will need to query the performance counters inside the CPUs. This is low level and very hardware specific, so you'll have to thunk to native code to get it. PAPI is the closest thing to a portable library for this task.

Be aware that context switches can change many of these internal CPU registers, so you'll need to do this query from inside your process. Querying the CPU counters from a different process will give you spurious results.

Remember also that CPU cycle count is not the same as (and on the x86, isn't even similar to) "number of instructions performed."

like image 45
Crashworks Avatar answered Sep 25 '22 01:09

Crashworks