c# – 测量函数调用的CPU周期
发布时间:2020-12-15 23:44:29 所属栏目:百科 来源:网络整理
导读:我正在寻找一种方法来测量线程上的函数调用所需的cpu周期. 伪代码示例: void HostFunction(){ var startTick = CurrentThread.CurrentTick; //does not exist ChildFunction(); var endTick = CurrentThread.CurrentTick; //does not exist var childFuncti
我正在寻找一种方法来测量线程上的函数调用所需的cpu周期.
伪代码示例: 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... } 我不想使用秒表或其他时间测量,因为它将包括线程正在休眠的任何时间,我不想测量.我只想衡量实际工作. 这个测量需要在运行时工作,就像在我的伪代码中一样,因为结果用于确定是否应该允许子函数继续运行(我的实例是一个插件类型的体系结构),因此一个分析工具赢了’帮帮我 解决方法
您可以发送
QueryThreadCycleTime().请查看链接以获取详细信息.
一些示例代码: 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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |