Skip to content

Instantly share code, notes, and snippets.

@ttsugriy
Created July 5, 2023 04:15
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 ttsugriy/45db22b2564745bedda05574c033c0b0 to your computer and use it in GitHub Desktop.
Save ttsugriy/45db22b2564745bedda05574c033c0b0 to your computer and use it in GitHub Desktop.
queue_test benchmarks
package queue
import (
"reflect"
"testing"
)
func copyUsingMod(elems []int, head int) []int {
oldLen := len(elems)
newElems := make([]int, oldLen)
for i := 0; i < oldLen; i++ {
newElems[i] = elems[(head+i)%oldLen]
}
return newElems
}
func copyUsingCopy(elems []int, head int) []int {
oldLen := len(elems)
newElems := make([]int, oldLen)
copy(newElems, elems[head:])
wrote := oldLen - head
copy(newElems[wrote:], elems[:head])
return newElems
}
func TestModCopy(t *testing.T) {
if !reflect.DeepEqual(copyUsingMod([]int{1}, 0), []int{1}) {
t.Error("1")
}
if !reflect.DeepEqual(copyUsingMod([]int{1, 2}, 0), []int{1, 2}) {
t.Error("2")
}
if !reflect.DeepEqual(copyUsingMod([]int{1, 2}, 1), []int{2, 1}) {
t.Error("3")
}
}
func TestCopyCopy(t *testing.T) {
if !reflect.DeepEqual(copyUsingCopy([]int{1}, 0), []int{1}) {
t.Error("1")
}
if !reflect.DeepEqual(copyUsingCopy([]int{1, 2}, 0), []int{1, 2}) {
t.Error("2")
}
if !reflect.DeepEqual(copyUsingCopy([]int{1, 2}, 1), []int{2, 1}) {
t.Error("3")
}
}
var elems = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
func TestModel(t *testing.T) {
for h := 0; h < len(elems); h++ {
if !reflect.DeepEqual(copyUsingMod(elems, h), copyUsingCopy(elems, h)) {
t.Error("model")
}
}
}
func BenchmarkModClone(b *testing.B) {
for i := 0; i < b.N; i++ {
for h := 0; h < len(elems); h++ {
copyUsingMod(elems, h)
}
}
}
func BenchmarkCopyClone(b *testing.B) {
for i := 0; i < b.N; i++ {
for h := 0; h < len(elems); h++ {
copyUsingCopy(elems, h)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment