Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure CPU cycles of a Function Call

Tags:

c#

.net

.net-4.5

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.

like image 728
Nathan A Avatar asked Dec 05 '22 23:12

Nathan A


1 Answers

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);

    }
}
like image 179
Hans Passant Avatar answered Dec 10 '22 12:12

Hans Passant