Skip to content

Instantly share code, notes, and snippets.

@honmaple
Last active April 6, 2023 14:57
Show Gist options
  • Save honmaple/acf9890a073eecc52767eb02e5601f95 to your computer and use it in GitHub Desktop.
Save honmaple/acf9890a073eecc52767eb02e5601f95 to your computer and use it in GitHub Desktop.
insert new element to array and sort compare to search and sort when insert
package main
import (
"math/rand"
"sort"
"testing"
"time"
)
func randNums() []int {
rand.Seed(time.Now().Unix())
return rand.Perm(len)
}
var nums = randNums()
var len = 500
func insertSort1() {
ss := make([]int, 0, len)
for _, num := range nums {
ss = append(ss, num)
}
sort.Ints(ss)
}
func BenchmarkSort1(b *testing.B) {
for i := 0; i < b.N; i++ {
insertSort1()
}
}
func insertSort2() {
ss := make([]int, 0, len)
for _, num := range nums {
i := sort.SearchInts(ss, num)
ss = append(ss, 0)
copy(ss[i+1:], ss[i:])
ss[i] = num
}
}
func BenchmarkSort2(b *testing.B) {
for i := 0; i < b.N; i++ {
insertSort2()
}
}
@honmaple
Copy link
Author

honmaple commented Apr 6, 2023

100

goos: darwin
goarch: amd64
pkg: my-tests
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
BenchmarkSort1-8   	  326121	      3391 ns/op
BenchmarkSort2-8   	  450127	      2657 ns/op
PASS
ok  	mytests	3.105s

200

goos: darwin
goarch: amd64
pkg: my-tests
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
BenchmarkSort1-8   	  148509	      8000 ns/op
BenchmarkSort2-8   	  186192	      6509 ns/op
PASS
ok  	my-tests	2.991s

500

goos: darwin
goarch: amd64
pkg: my-tests
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
BenchmarkSort1-8   	   42337	     27673 ns/op
BenchmarkSort2-8   	   39577	     31739 ns/op
PASS
ok  	my-tests	3.992s

1000

goos: darwin
goarch: amd64
pkg: my-tests
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
BenchmarkSort1-8   	   17462	     67512 ns/op
BenchmarkSort2-8   	   14341	     85077 ns/op
PASS
ok  	my-tests	2.966s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment