diff --git a/decimal.go b/decimal.go index 9f62fea..0d2425f 100644 --- a/decimal.go +++ b/decimal.go @@ -294,6 +294,13 @@ func (d Decimal) Div(d2 Decimal) Decimal { // +1 if d > d2 // func (d Decimal) Cmp(d2 Decimal) int { + d.ensureInitialized() + d2.ensureInitialized() + + if d.exp == d2.exp { + return d.value.Cmp(d2.value) + } + baseExp := min(d.exp, d2.exp) rd := d.rescale(baseExp) rd2 := d2.rescale(baseExp) diff --git a/decimal_test.go b/decimal_test.go index f3169f3..ecfb5ad 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "encoding/xml" "math" + "sort" "strconv" "strings" "testing" @@ -957,3 +958,19 @@ func didPanic(f func()) bool { return ret } + +type DecimalSlice []Decimal + +func (p DecimalSlice) Len() int { return len(p) } +func (p DecimalSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +func (p DecimalSlice) Less(i, j int) bool { return p[i].Cmp(p[j]) < 0 } +func Benchmark_Cmp(b *testing.B) { + decimals := DecimalSlice([]Decimal{}) + for i := 0; i < 1000000; i++ { + decimals = append(decimals, New(int64(i), 0)) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + sort.Sort(decimals) + } +}