Build the C # Method Before You Run

I measure the code speed as follows:

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

But the first call to DoSomething () is slow because the code is compiling. A temporary solution is to measure the second call as follows:

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

Is there a way to precompile DoSomethig () without a first call?

+6
source share
2 answers

The documentation does not explicitly state this, but according to this article (among other things) you can use RuntimeHelpers.PrepareMethod to precompile the method.

To think through my comment (above), an example code is provided:

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

Update

Here is a more general (albeit somewhat fragile) solution that will also consider instance instances:

 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; } 
+4
source

The reason you see this time difference is because the runtime compiles the method to execute before the first call, and when it is called a second time, all that is required to run the method is already compiled. You can use ngen.exe for this task. It compiles il to native exe before execution and reduces startup time.

In your specific scenario, I believe that ngen.exe will be the right tool for the job, as it can be fired as a post build event to compile your builds well in advance and be ready when you need it. If you use PrepareMethod, you will still have a JIT delay on the methods when you run your tests, and not just when they are called.

0
source

Source: https://habr.com/ru/post/972814/


All Articles