Created
May 21, 2017 21:23
-
-
Save alanta/944c5d3960a19ca48e6817c3f4c125f6 to your computer and use it in GitHub Desktop.
benchmark tests for rounding floats in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Linq; | |
| using BenchmarkDotNet.Attributes; | |
| using BenchmarkDotNet.Running; | |
| namespace ClassLibrary2 | |
| { | |
| public class Rounding | |
| { | |
| private const int N = 100000; | |
| private readonly float[] data; | |
| public Rounding() | |
| { | |
| data = new float[N]; | |
| var random = new Random(42); | |
| for(var x=0; x<N; x++) | |
| { | |
| data[x] = random.Next(-25, 25)/10f; | |
| } | |
| } | |
| [Benchmark] | |
| public int[] Round() => data.Select(x => (int)Math.Round(x, 0, MidpointRounding.AwayFromZero)).ToArray(); | |
| [Benchmark] | |
| public int[] AddAndCast() => data.Select( x => (int)(x-0.5f)).ToArray(); | |
| [Benchmark] | |
| public int[] AddAndCast2() => data.Select(x => x >= 0 ? (int)(x + 0.5f) : (int)(x - 0.5f)).ToArray(); | |
| [Benchmark] | |
| public int[] RoundFast() => data.Select(RoundFast).ToArray(); | |
| [Benchmark] | |
| public int[] ConvertToInt() => data.Select(Convert.ToInt32).ToArray(); | |
| public static int RoundFast(float num) | |
| { | |
| return (int)(num + 0.5f * (-1 + 2 * (1 + num - (num + 1) % num) / num)); | |
| } | |
| } | |
| public class Class1 | |
| { | |
| public static void Main(string[] args) | |
| { | |
| var summary = BenchmarkRunner.Run<Rounding>(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment