I'm looking for a way to measure the cpu cycles a function call on a thread takes.
Example pseudo code:
void HostFunction()
{
var startTick = CurrentThread.CurrentTick; //does not exist
ChildFunction();
var endTick = CurrentThread.CurrentTick; //does not exist
var childFunctionCost = endTick - startTick;
}
void ChildFunction()
{
//Do whatever...
Thread.Sleep(3000);
//Do some more...
}
I don't want to use a Stopwatch or some other time measurement, because it would include any time that the thread is sleeping, which I do not want to measure. I only want to measure real work.
This measurement needs to work at runtime, as in my pseudo code, as the results are used to determine if the child function should be allowed to continue to run (my real case is a plugin-type architecture), so a profiling tool won't help me.
You can pinvoke QueryThreadCycleTime(). Check the link for details.
Some sample code:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class Program {
static void Main(string[] args) {
ulong start, end;
start = NativeMethods.GetThreadCycles();
System.Threading.Thread.Sleep(1000);
end = NativeMethods.GetThreadCycles();
ulong cycles = end - start;
Debug.Assert(cycles < 200000);
}
static class NativeMethods {
public static ulong GetThreadCycles() {
ulong cycles;
if (!QueryThreadCycleTime(PseudoHandle, out cycles))
throw new System.ComponentModel.Win32Exception();
return cycles;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool QueryThreadCycleTime(IntPtr hThread, out ulong cycles);
private static readonly IntPtr PseudoHandle = (IntPtr)(-2);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With