Skip to content

Instantly share code, notes, and snippets.

@tailnode
Created May 28, 2017 02:31
Show Gist options
  • Save tailnode/b481a14272773d504781721bf9bfd733 to your computer and use it in GitHub Desktop.
Save tailnode/b481a14272773d504781721bf9bfd733 to your computer and use it in GitHub Desktop.
// 测试 RoundRobin 中通过取余和通过判断大小的两种方法的性能
package main
import "testing"
type roundrobin struct {
i int // 服务地址索引
servers []string // 可用的服务地址
}
const count = 10
func (r *roundrobin) module() string {
s := r.servers[r.i]
r.i++
r.i %= len(r.servers)
return s
}
func (r *roundrobin) check() string {
s := r.servers[r.i]
r.i++
if r.i == len(r.servers) {
r.i = 0
}
return s
}
func BenchmarkModule(b *testing.B) {
var r = roundrobin{
servers: make([]string, count),
}
for i := 0; i < b.N; i++ {
r.module()
}
}
func BenchmarkCheck(b *testing.B) {
var r = roundrobin{
servers: make([]string, count),
}
for i := 0; i < b.N; i++ {
r.check()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment