gpt4 book ai didi

c# - 测量函数调用的 CPU 周期

转载 作者:太空狗 更新时间:2023-10-30 00:07:21 31 4
gpt4 key购买 nike

我正在寻找一种方法来测量线程上的函数调用所花费的 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);

}
}

关于c# - 测量函数调用的 CPU 周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26618991/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com