Skip to content

Instantly share code, notes, and snippets.

@azyobuzin
Last active June 22, 2018 15:26
Show Gist options
  • Save azyobuzin/74788512608f875279cba7db0b5591ea to your computer and use it in GitHub Desktop.
Save azyobuzin/74788512608f875279cba7db0b5591ea to your computer and use it in GitHub Desktop.
これが最強の桁数カウントだ
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 Median
UseToString 123.456 441.00 ns 5.8036 ns 5.1447 ns 440.59 ns
UseDecimalUnsafe 123.456 47.29 ns 0.5086 ns 0.4508 ns 47.27 ns
UseDecimalSafe 123.456 95.44 ns 2.1743 ns 5.0394 ns 93.50 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) UseDecimalUnsafe()
{
var tmpDouble = this.Source;
var seisuCount = 0;
while (tmpDouble >= 1.0)
{
tmpDouble /= 10.0;
seisuCount++;
}
int syosuCount;
unsafe
{
var tmpDecimal = (decimal)this.Source;
var flags = *(uint*)&tmpDecimal;
syosuCount = (int)((flags >> 16) & 0xFF);
}
return (seisuCount, syosuCount);
}
[Benchmark]
public (int seisu, int syosu) UseDecimalSafe()
{
var tmpDouble = this.Source;
var seisuCount = 0;
while (tmpDouble >= 1.0)
{
tmpDouble /= 10.0;
seisuCount++;
}
var tmpDecimal = (decimal)this.Source;
var flags = (uint)Decimal.GetBits((decimal)this.Source)[3];
var syosuCount = (int)((flags >> 16) & 0xFF);
return (seisuCount, syosuCount);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment