Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Program
- {
- static void Main(string[] args)
- {
- var values = new List<(double x, double y)>();
- Stopwatch compileTime = Stopwatch.StartNew();
- string ftext = "Math.Sin(x)+0.3*Math.Sin(15*x)";
- Func<double, double> f = CompileFunc(ftext);
- compileTime.Stop();
- Stopwatch computeTime = Stopwatch.StartNew();
- for (double x = 0; x < 1_000_000 * 2 * Math.PI; x += 0.1)
- values.Add((x, f(x)));
- computeTime.Stop();
- Console.WriteLine($"Compile time: {compileTime.ElapsedMilliseconds} ms, compute time: {computeTime.ElapsedMilliseconds} ms");
- Console.WriteLine("Computed values");
- foreach (var pair in values.Take(10))
- Console.WriteLine($"f({pair.x}) = {pair.y}");
- Console.ReadKey();
- }
- static string boilerplate = @"using System; public static class C {{ public static double F(double x) {{ return {0}; }} }}";
- static Func<double, double> CompileFunc(string source)
- {
- var classSource = string.Format(boilerplate, source);
- var asm = CompileToAssembly(classSource);
- var mi = asm.GetType("C").GetMethod("F");
- return (Func<double, double>)Delegate.CreateDelegate(typeof(Func<double, double>), mi);
- }
- static Assembly CompileToAssembly(string source)
- {
- CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(
- new CompilerParameters()
- {
- ReferencedAssemblies = { "System.dll" },
- GenerateInMemory = true
- }, source);
- if (cr.Errors.HasErrors)
- throw new ArgumentException("Invalid source");
- return cr.CompiledAssembly;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement