|
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace LambdaTests
{
class ClosureBenchmark : Benchmark
{
static double[] A;
static double[] B;
public static void Test()
{
var me = new ClosureBenchmark();
var c = new double[100];
Init(c);
for (var i = 0; i < 10; i++)
{
var lambda = LambdaBenchmark(c);
var normal = NormalBenchmark(c);
me.lambdaResults.Add(lambda);
me.normalResults.Add(normal);
}
me.PrintTable();
}
static void Init(double[] c)
{
var r = new Random();
A = new double[LENGTH];
B = new double[LENGTH];
for (var i = 0; i < LENGTH; i++)
{
A[i] = r.NextDouble();
B[i] = r.NextDouble();
}
for (var i = 0; i < c.Length; i++)
c[i] = r.NextDouble();
}
static long LambdaBenchmark(double[] c)
{
double coeff = 0.0;
Func<double> Perform = () =>
{
var sum = 0.0;
for (var i = 0; i < LENGTH; i++)
sum += coeff * A[i] * B[i];
return sum;
};
var iterations = new double[c.Length];
var timing = new Stopwatch();
timing.Start();
for (var j = 0; j < iterations.Length; j++)
{
coeff = c[j];
iterations[j] = Perform();
}
timing.Stop();
Console.WriteLine("Time for Lambda-Benchmark: \t {0}ms", timing.ElapsedMilliseconds);
return timing.ElapsedMilliseconds;
}
static long NormalBenchmark(double[] c)
{
var iterations = new double[c.Length];
var timing = new Stopwatch();
timing.Start();
for (var j = 0; j < iterations.Length; j++)
iterations[j] = NormalPerform(c[j]);
timing.Stop();
Console.WriteLine("Time for Normal-Benchmark: \t {0}ms", timing.ElapsedMilliseconds);
return timing.ElapsedMilliseconds;
}
static double NormalPerform(double c)
{
var sum = 0.0;
for (var i = 0; i < LENGTH; i++)
sum += c * A[i] * B[i];
return sum;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Florian lives in Munich, Germany. He started his programming career with Perl. After programming C/C++ for some years he discovered his favorite programming language C#. He did work at Siemens as a programmer until he decided to study Physics.
During his studies he worked as an IT consultant for various companies. After graduating with a PhD in theoretical particle Physics he is working as a senior technical consultant in the field of home automation and IoT.
Florian has been giving lectures in C#, HTML5 with CSS3 and JavaScript, software design, and other topics. He is regularly giving talks at user groups, conferences, and companies. He is actively contributing to open-source projects. Florian is the maintainer of AngleSharp, a completely managed browser engine.