Skip to content

Instantly share code, notes, and snippets.

@azyobuzin
Last active June 22, 2018 14:55
Show Gist options
  • Save azyobuzin/f3d854c7a013316e67fd023e9d7a6a62 to your computer and use it in GitHub Desktop.
Save azyobuzin/f3d854c7a013316e67fd023e9d7a6a62 to your computer and use it in GitHub Desktop.
Decimal 割りまくる
BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17692
Intel Core i7-3770 CPU 3.40GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores
  [Host]     : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.3062.0
  DefaultJob : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.3062.0

Method Source Mean Error StdDev
UseToString 123.456 438.9 ns 7.701 ns 7.204 ns
UseDecimal 123.456 1,252.4 ns 11.789 ns 9.845 ns
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<Benchmark>();
}
}
public class Benchmark
{
[Params(123.456)]
public double Source;
[Benchmark]
public (int seisu, int syosu) UseToString()
{
var xStr = this.Source.ToString("F99", System.Globalization.CultureInfo.InvariantCulture);
var dotIndex = xStr.IndexOf('.');
var syosuCount = 0;
for (var i = dotIndex + 1; i < xStr.Length; i++)
{
if (xStr[i] != '0') syosuCount = i - dotIndex;
}
return (dotIndex, syosuCount);
}
[Benchmark]
public (int seisu, int syosu) UseDecimal()
{
var x = (decimal)this.Source;
// 整数部
var seisuCount = 0;
var tmp1 = x;
while (tmp1 >= 1m)
{
tmp1 /= 10m;
seisuCount++;
}
// 小数部
var syosuCount = 0;
var tmp2 = Math.Abs(x) % 1.0m;
while (tmp2 > 0m)
{
tmp2 = tmp2 * 10m % 1.0m;
syosuCount++;
}
return (seisuCount, syosuCount);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment