Advertisement
Guest User

Untitled

a guest
Mar 11th, 2018
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1.     class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             var values = new List<(double x, double y)>();
  6.  
  7.             Stopwatch compileTime = Stopwatch.StartNew();
  8.             string ftext = "Math.Sin(x)+0.3*Math.Sin(15*x)";
  9.             Func<double, double> f = CompileFunc(ftext);
  10.             compileTime.Stop();
  11.  
  12.             Stopwatch computeTime = Stopwatch.StartNew();
  13.             for (double x = 0; x < 1_000_000 * 2 * Math.PI; x += 0.1)
  14.                 values.Add((x, f(x)));
  15.             computeTime.Stop();
  16.  
  17.             Console.WriteLine($"Compile time: {compileTime.ElapsedMilliseconds} ms, compute time: {computeTime.ElapsedMilliseconds} ms");
  18.             Console.WriteLine("Computed values");
  19.             foreach (var pair in values.Take(10))
  20.                 Console.WriteLine($"f({pair.x}) = {pair.y}");
  21.             Console.ReadKey();
  22.         }
  23.  
  24.         static string boilerplate = @"using System; public static class C {{ public static double F(double x) {{ return {0}; }} }}";
  25.  
  26.         static Func<double, double> CompileFunc(string source)
  27.         {
  28.             var classSource = string.Format(boilerplate, source);
  29.             var asm = CompileToAssembly(classSource);
  30.             var mi = asm.GetType("C").GetMethod("F");
  31.             return (Func<double, double>)Delegate.CreateDelegate(typeof(Func<double, double>), mi);
  32.         }
  33.  
  34.         static Assembly CompileToAssembly(string source)
  35.         {
  36.             CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(
  37.                 new CompilerParameters()
  38.                 {
  39.                     ReferencedAssemblies = { "System.dll" },
  40.                     GenerateInMemory = true
  41.                 }, source);
  42.  
  43.             if (cr.Errors.HasErrors)
  44.                 throw new ArgumentException("Invalid source");
  45.  
  46.             return cr.CompiledAssembly;
  47.         }
  48.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement