From 31945563d89f9d598b8871d88b31bf4d5d7cc434 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Thu, 15 Sep 2022 01:30:08 +0900 Subject: [PATCH] internal/atlas: optimize adjustDestinationPixel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ``` go test -bench=BenchmarkAdjustPixel -run=^$ -count=5 ./internal/atlas/ ``` ``` name old time/op new time/op delta AdjustPixel-8 2.59ns ± 1% 2.12ns ± 1% -18.16% (p=0.008 n=5+5) ``` --- internal/atlas/image.go | 7 +++++-- internal/atlas/image_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/internal/atlas/image.go b/internal/atlas/image.go index bbb314abc..b2dac9270 100644 --- a/internal/atlas/image.go +++ b/internal/atlas/image.go @@ -17,7 +17,6 @@ package atlas import ( "fmt" "image" - "math" "runtime" "sync" @@ -805,7 +804,11 @@ func adjustDestinationPixel(x float32) float32 { // float32(math.Floor((float64(x)+1.0/6.0)*3) / 3) // // The actual implementation is more optimized than the above implementation. - ix := float32(math.Floor(float64(x))) + var ix float32 + ix = float32(int(x)) + if x < 0 && x != ix { + ix -= 1 + } frac := x - ix switch { case frac < 3.0/16.0: diff --git a/internal/atlas/image_test.go b/internal/atlas/image_test.go index 24335a98b..7d6041797 100644 --- a/internal/atlas/image_test.go +++ b/internal/atlas/image_test.go @@ -737,6 +737,40 @@ func TestImageWritePixelsModify(t *testing.T) { } } +func TestAdjustPixel(t *testing.T) { + tests := []struct { + X float32 + Y float32 + Delta float32 + }{ + { + X: -0.1, + Y: 0.9, + Delta: 1, + }, + { + X: -1, + Y: 0, + Delta: 1, + }, + { + X: -1.9, + Y: 1.1, + Delta: 3, + }, + { + X: -2, + Y: 1, + Delta: 3, + }, + } + for _, tc := range tests { + if rx, ry := atlas.AdjustDestinationPixelForTesting(tc.X)+tc.Delta, atlas.AdjustDestinationPixelForTesting(tc.Y); rx != ry { + t.Errorf("adjustDestinationPixel(%f) + 1 must equal to adjustDestinationPixel(%f) but not (%f vs %f)", tc.X, tc.Y, rx, ry) + } + } +} + func BenchmarkAdjustPixel(b *testing.B) { for i := 0; i < b.N; i++ { atlas.AdjustDestinationPixelForTesting(float32(i) / 17)