Skip to content

Instantly share code, notes, and snippets.

@stanim
Created July 4, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stanim/251ef4f0d71a3dc11287 to your computer and use it in GitHub Desktop.
Save stanim/251ef4f0d71a3dc11287 to your computer and use it in GitHub Desktop.
$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkIntersectWithZR 50000000 29.5 ns/op
BenchmarkIntersectWithoutZR 50000000 35.5 ns/op
ok stani.be/temp/polyclip/zr 3.318s
35.5/29.5 = 1,20
package zr
type Point struct {
X, Y float64
}
type Rectangle struct {
Min, Max Point
}
var ZR Rectangle
func (r Rectangle) Intersect1(s Rectangle) Rectangle {
if r.Min.X < s.Min.X {
r.Min.X = s.Min.X
}
if r.Min.Y < s.Min.Y {
r.Min.Y = s.Min.Y
}
if r.Max.X > s.Max.X {
r.Max.X = s.Max.X
}
if r.Max.Y > s.Max.Y {
r.Max.Y = s.Max.Y
}
if r.Min.X > r.Max.X || r.Min.Y > r.Max.Y {
return ZR
}
return r
}
func (r Rectangle) Intersect2(s Rectangle) Rectangle {
if r.Min.X < s.Min.X {
r.Min.X = s.Min.X
}
if r.Min.Y < s.Min.Y {
r.Min.Y = s.Min.Y
}
if r.Max.X > s.Max.X {
r.Max.X = s.Max.X
}
if r.Max.Y > s.Max.Y {
r.Max.Y = s.Max.Y
}
if r.Min.X > r.Max.X || r.Min.Y > r.Max.Y {
return Rectangle{}
}
return r
}
package zr
import "testing"
var result1, result2 bool
func BenchmarkIntersectWithZR(b *testing.B) {
r := Rectangle{Point{0, 0}, Point{1, 1}}
s := Rectangle{Point{2, 2}, Point{3, 3}}
for n := 0; n < b.N; n++ {
i := r.Intersect1(s)
result1 = i == ZR
}
}
func BenchmarkIntersectWithoutZR(b *testing.B) {
r := Rectangle{Point{0, 0}, Point{1, 1}}
s := Rectangle{Point{2, 2}, Point{3, 3}}
for n := 0; n < b.N; n++ {
i := r.Intersect2(s)
result2 = i == Rectangle{}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment