gpt4 book ai didi

c# - 执行前预编译 C# 方法

转载 作者:太空狗 更新时间:2023-10-29 21:44:32 26 4
gpt4 key购买 nike

我这样测量代码速度:

var sw = new Stopwatch();
sw.Start();
DoSomething();
sw.Stop();
AddLog("Method speed is (ms): "+sw.ElapsedMilliseconds);

但是第一次调用 DoSomething() 很慢,因为代码正在编译。解决方法是像这样测量第二次调用的速度:

var sw = new Stopwatch();
DoSomething();
sw.Start();
DoSomething();
sw.Stop();
AddLog("Method speed is (ms): "+sw.ElapsedMilliseconds);

有没有办法在不先调用的情况下预编译 DoSomethig()?

最佳答案

The documentation does not unequivocally state so, but according to this article (among others) you can use the RuntimeHelpers.PrepareMethod to precompile a method.

为了详细说明我的评论(上述),这里有一个代码示例:

static void WarmUp()
{
var handle = typeof (Program).GetMethod("DoSomething").MethodHandle;
RuntimeHelpers.PrepareMethod(handle);
}

更新

这是一个更通用(虽然有点脆弱)的解决方案,它也将考虑实例成员:

public static class MethodWarmerUper
{
public static void WarmUp(string methodName)
{
var handle = FindMethodWithName(methodName).MethodHandle;
RuntimeHelpers.PrepareMethod(handle);
}

private static MethodInfo FindMethodWithName(string methodName)
{
return
Assembly.GetExecutingAssembly()
.GetTypes()
.SelectMany(type => type.GetMethods(MethodBindingFlags))
.FirstOrDefault(method => method.Name == methodName);
}

private const BindingFlags MethodBindingFlags =
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static;
}

关于c# - 执行前预编译 C# 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24948984/

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