func BenchmarkGorillaMux(b *testing.B) { b.StopTimer() http.DefaultServeMux = http.NewServeMux() r := mux.NewRouter() r.HandleFunc("/heroku/resources", fakehandler). Methods("POST") r.HandleFunc("/heroku/delete", fakehandler). Methods("DELETE") ts := httptest.NewServer(r) defer ts.Close() b.StartTimer() for i := 0; i < b.N; i++ { res, err := http.Post(ts.URL+"/heroku/resources", "text", strings.NewReader("")) if err != nil { b.Fatal("Post:", err) } _, err = ioutil.ReadAll(res.Body) if err != nil { b.Fatal("ReadAll:", err) } } b.StopTimer() }
func BenchmarkConnStress(b *testing.B) { const workers = 16 cluster := createCluster() cluster.NumConns = 1 session := createSessionFromCluster(cluster, b) defer session.Close() if err := createTable(session, "CREATE TABLE IF NOT EXISTS conn_stress (id int primary key)"); err != nil { b.Fatal(err) } var seed uint64 writer := func(pb *testing.PB) { seed := atomic.AddUint64(&seed, 1) var i uint64 = 0 for pb.Next() { if err := session.Query("insert into conn_stress (id) values (?)", i*seed).Exec(); err != nil { b.Error(err) return } i++ } } b.SetParallelism(workers) b.RunParallel(writer) }
func benchPutItemParallel(p, c int, b *testing.B) { svc := dynamodb.New(&aws.Config{ DisableSSL: aws.Bool(true), }) av, err := dynamodbattribute.ConvertToMap(dbItem{Key: "MyKey", Data: "MyData"}) if err != nil { b.Fatal("expect no ConvertToMap errors", err) } params := &dynamodb.PutItemInput{ Item: av, TableName: aws.String(testTableName), } b.N = c b.ResetTimer() b.SetParallelism(p) b.RunParallel(func(pb *testing.PB) { for pb.Next() { _, err = svc.PutItem(params) if err != nil { b.Error("expect no request errors", err) } } }) }
func BenchmarkFilterPatterns(b *testing.B) { patterns := []string{ "sdk/*", "*.html", } lines := extractTestLines(b) var c uint b.ResetTimer() for i := 0; i < b.N; i++ { c = 0 for _, line := range lines { match, err := filter.List(patterns, line) if err != nil { b.Fatal(err) } if match { c++ } } if c != 22185 { b.Fatalf("wrong number of matches: expected 22185, got %d", c) } } }
func BenchmarkSmall(t *testing.B) { for i := 0; i < t.N; i++ { if _, err := ParseString(SmallJson); err != nil { t.Fatal(err) } } }
func benchmarkBTreeSetRollbackFiler(b *testing.B, sz int) { dir, testDbName := temp() defer os.RemoveAll(dir) f, err := os.OpenFile(testDbName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) if err != nil { b.Fatal(err) } defer f.Close() g := NewSimpleFileFiler(f) var filer *RollbackFiler if filer, err = NewRollbackFiler( g, func(sz int64) error { if err = g.Truncate(sz); err != nil { return err } return g.Sync() }, g, ); err != nil { b.Error(err) return } benchmarkBTreeSetFiler(b, filer, sz) }
func benchmarkEndToEnd(dial func() (*Client, error), b *testing.B) { b.StopTimer() once.Do(startServer) client, err := dial() if err != nil { b.Fatal("error dialing:", err) } // Synchronous calls args := &Args{7, 8} procs := runtime.GOMAXPROCS(-1) N := int32(b.N) var wg sync.WaitGroup wg.Add(procs) b.StartTimer() for p := 0; p < procs; p++ { go func() { reply := new(Reply) for atomic.AddInt32(&N, -1) >= 0 { err := client.Call("Arith.Add", args, reply) if err != nil { b.Fatalf("rpc error: Add: expected no error but got string %q", err.Error()) } if reply.C != args.A+args.B { b.Fatalf("rpc error: Add: expected %d got %d", reply.C, args.A+args.B) } } wg.Done() }() } wg.Wait() }
// Benchmarking raw mgo queries. func BenchmarkAppendRaw(b *testing.B) { sess, err := db.Open(Adapter, settings) if err != nil { b.Fatal(err) } defer sess.Close() artist, err := sess.Collection("artist") artist.Truncate() driver := sess.Driver().(*mgo.Session) mgodb := driver.DB(database) col := mgodb.C("artist") b.ResetTimer() for i := 0; i < b.N; i++ { err := col.Insert(map[string]string{"name": "Hayao Miyazaki"}) if err != nil { b.Fatal(err) } } }
func BenchmarkInterfaceAddrs(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := InterfaceAddrs(); err != nil { b.Fatal(err) } } }
func BenchmarkLanguage(b *testing.B) { b.StopTimer() tst := []string{ "language.go", "testdata/main.go", } var d0 []string for _, s := range tst { if d, err := ioutil.ReadFile(s); err != nil { b.Errorf("Couldn't load file %s: %s", s, err) } else { d0 = append(d0, string(d)) } } b.StartTimer() for i := 0; i < b.N; i++ { for j := range d0 { lp, err := NewLanguageParser("testdata/Go.tmLanguage", d0[j]) if err != nil { b.Fatal(err) return } lp.Parse() } } fmt.Println(util.Prof) }
func BenchmarkAll(b *testing.B) { stds, err := exec.Command("go", "list", "std").Output() if err != nil { b.Fatal(err) } b.ResetTimer() pkgNames := strings.Fields(string(stds)) for _, c := range contexts { c.Compiler = build.Default.Compiler } for i := 0; i < b.N; i++ { for _, context := range contexts { w := NewWalker(context, filepath.Join(build.Default.GOROOT, "src")) for _, name := range pkgNames { if name != "unsafe" && !strings.HasPrefix(name, "cmd/") { pkg, _ := w.Import(name) w.export(pkg) } } w.Features() } } }
func BenchmarkDecodeStruct(b *testing.B) { type s1 struct { Atom types.Atom priv0 int Uint8 uint8 Uint16 uint16 Uint32 uint32 priv1 string Byte byte Int int priv2 *s1 List []s1 Binary []byte } data := []byte{ 131, 104, 8, 100, 0, 12, 116, 104, 105, 115, 32, 105, 115, 32, 97, 116, 111, 109, 97, 255, 98, 0, 0, 255, 255, 110, 4, 0, 255, 255, 255, 255, 97, 128, 98, 255, 255, 253, 102, 106, 107, 0, 5, 1, 2, 3, 4, 5, } in := bytes.NewBuffer(data) var v s1 err := Decode(in, &v) if err != nil { b.Fatal(err) } else if l := in.Len(); l != 0 { b.Fatalf("buffer len %d", l) } for i := 0; i < b.N; i++ { in = bytes.NewBuffer(data) err = Decode(in, &v) } }
func BenchmarkUsersProd(b *testing.B) { prodfile := "./prods/users.prod" text, err := ioutil.ReadFile(prodfile) if err != nil { b.Fatal(err) } seed := uint64(time.Now().UnixNano()) s := parsec.NewScanner(text) root, _ := Y(s) scope := root.(common.Scope) nterms := scope["_nonterminals"].(common.NTForms) scope = BuildContext(scope, seed, "./bags", prodfile) b.ResetTimer() out := 0 for i := 0; i < b.N; i++ { scope = scope.RebuildContext() if val, ok := EvalForms("root", scope, nterms["s"]).(string); !ok { b.Fatalf("not string `%v`\n", val) } else { out += len(val) } } b.SetBytes(int64(float64(out) / float64(b.N))) }
// BenchmarkAccessorSetReflection provides a baseline for accessor performance func BenchmarkAccessorSetReflection(b *testing.B) { obj := &InternalObject{ InternalTypeMeta{ Namespace: "bar", Name: "foo", GenerateName: "prefix", UID: "uid", APIVersion: "a", Kind: "b", ResourceVersion: "1", SelfLink: "some/place/only/we/know", Labels: map[string]string{"foo": "bar"}, Annotations: map[string]string{"x": "y"}, }, } b.ResetTimer() for i := 0; i < b.N; i++ { acc, err := meta.Accessor(obj) if err != nil { b.Fatal(err) } acc.SetNamespace("something") } b.StopTimer() }
func benchmarkIterOnBatch(b *testing.B, writes int) { stopper := stop.NewStopper() defer stopper.Stop() engine := createTestEngine(stopper) for i := 0; i < writes; i++ { if err := engine.Put(makeKey(i), []byte(strconv.Itoa(i))); err != nil { b.Fatal(err) } } batch := engine.NewBatch() defer batch.Close() for i := 0; i < writes; i++ { if err := batch.Clear(makeKey(i)); err != nil { b.Fatal(err) } } r := rand.New(rand.NewSource(5)) b.ResetTimer() for i := 0; i < b.N; i++ { key := makeKey(r.Intn(writes)) iter := batch.NewIterator(true) iter.Seek(key) iter.Close() } }
func BenchmarkEncodeRGBOpaque(b *testing.B) { b.StopTimer() img := image.NewRGBA(image.Rect(0, 0, 640, 480)) // Set all pixels to 0xFF alpha to force opaque mode. bo := img.Bounds() rnd := rand.New(rand.NewSource(123)) for y := bo.Min.Y; y < bo.Max.Y; y++ { for x := bo.Min.X; x < bo.Max.X; x++ { img.Set(x, y, color.RGBA{ uint8(rnd.Intn(256)), uint8(rnd.Intn(256)), uint8(rnd.Intn(256)), 255}) } } if !img.Opaque() { b.Fatal("expected image to be opaque") } b.SetBytes(640 * 480 * 4) b.StartTimer() options := &Options{Quality: 90} for i := 0; i < b.N; i++ { Encode(ioutil.Discard, img, options) } }
func BenchmarkNoHack(b *testing.B) { client, srv := net.Pipe() done := make(chan struct{}) req := []byte("GET /foo\nHost: /var/run/docker.sock\nUser-Agent: Docker\n") read := make([]byte, 4096) b.SetBytes(int64(len(req) * 30)) go func() { for { if _, err := srv.Write(req); err != nil { srv.Close() break } } close(done) }() for i := 0; i < b.N; i++ { for i := 0; i < 30; i++ { if _, err := client.Read(read); err != nil && err != io.EOF { b.Fatal(err) } } } client.Close() <-done }
func BenchmarkMatches(b *testing.B) { db := readonlyDB() var p *Prefix var err error for p == nil || err != nil { ip := make([]byte, 4) for i := range ip { ip[i] = byte(rand.Int()) } p = db.Realm("prod").Prefix(&net.IPNet{net.IP(ip), net.CIDRMask(32, 32)}) p2, err := p.GetLongestMatch() if err == nil && reflect.DeepEqual(p, p2) { err = errors.New("") } else { p = p2 } } b.ResetTimer() for n := 0; n < b.N; n++ { if _, err := p.GetMatches(); err != nil { b.Fatal(err) } } }
func benchmarkBTreeSetACIDFiler(b *testing.B, sz int) { dir, testDbName := temp() defer os.RemoveAll(dir) f, err := os.OpenFile(testDbName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) if err != nil { b.Fatal(err) } defer f.Close() wal, err := os.OpenFile(testDbName+".wal", os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) if err != nil { b.Fatal(err) } defer wal.Close() filer, err := NewACIDFiler(NewSimpleFileFiler(f), wal) if err != nil { b.Error(err) return } benchmarkBTreeSetFiler(b, filer, sz) }
// This benchmark is mostly useful for very manual inspection and // debugging, so it's off by default. func BenchmarkInsertions(b *testing.B) { var prefixes []*net.IPNet for _, l := range []int{32, 24, 16, 8} { for n := 0; n < 1000; n++ { b := l / 8 ip := make([]byte, 4) for i := 0; i < b; i++ { ip[i] = byte(rand.Int()) } prefixes = append(prefixes, &net.IPNet{net.IP(ip), net.CIDRMask(l, 32)}) } } b.ResetTimer() for n := 0; n < b.N; n++ { db, err := New(":memory:") if err != nil { b.Fatal("Cannot create in-memory DB:", err) } r := db.Realm("prod") if err = r.Create(); err != nil { b.Fatalf("Creating realm: %s", err) } for _, p := range prefixes { r.Prefix(p).Create() } db.Close() } }
func BenchmarkFilterLines(b *testing.B) { pattern := "sdk/*/cpp/*/*vars.html" lines := extractTestLines(b) var c uint b.ResetTimer() for i := 0; i < b.N; i++ { c = 0 for _, line := range lines { match, err := filter.Match(pattern, line) if err != nil { b.Fatal(err) } if match { c++ } } if c != 3 { b.Fatalf("wrong number of matches: expected 3, got %d", c) } } }
func BenchmarkConsecutivePut(b *testing.B) { r := rand.New() var blocks [][]byte var keys []datastore.Key for i := 0; i < b.N; i++ { blk := make([]byte, 256*1024) r.Read(blk) blocks = append(blocks, blk) key := base32.StdEncoding.EncodeToString(blk[:8]) keys = append(keys, datastore.NewKey(key)) } temp, cleanup := tempdir(b) defer cleanup() fs, err := flatfs.New(temp, 2) if err != nil { b.Fatalf("New fail: %v\n", err) } b.ResetTimer() for i := 0; i < b.N; i++ { err := fs.Put(keys[i], blocks[i]) if err != nil { b.Fatal(err) } } }
func BenchmarkHandlerCall(b *testing.B) { fn := func(params *jsonrpc2.EmptyParams) (interface{}, error) { return nil, nil } handler := handler{ method: reflect.ValueOf(fn), params: reflect.New(reflect.ValueOf(fn).Type().In(0).Elem()).Interface().(jsonrpc2.Params), } data, _ := json.Marshal(&jsonrpc2.EmptyParams{}) params, err := handler.DecodeParams(data) if err != nil { b.Fatal(err.Error()) } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { handler.Call(params) } }
func BenchmarkDecode(b *testing.B) { fix := testMap(100) env := &Env{} type X struct { f string } // half a json for i, kv := range fix { if i%2 != 0 { if err := env.SetJson(kv[0], X{kv[1]}); err != nil { b.Fatal(err) } continue } env.Set(kv[0], kv[1]) } var writer bytes.Buffer env.Encode(&writer) denv := &Env{} reader := bytes.NewReader(writer.Bytes()) b.ResetTimer() for i := 0; i < b.N; i++ { err := denv.Decode(reader) if err != nil { b.Fatal(err) } reader.Seek(0, 0) } }
func BenchmarkPublishJsonStruct(b *testing.B) { // stop benchmark for set-up b.StopTimer() s := test.RunDefaultServer() defer s.Shutdown() ec := NewJsonEncodedConn(b) defer ec.Close() ch := make(chan bool) me := &person{Name: "derek", Age: 22, Address: "140 New Montgomery St"} me.Children = make(map[string]*person) me.Children["sam"] = &person{Name: "sam", Age: 19, Address: "140 New Montgomery St"} me.Children["meg"] = &person{Name: "meg", Age: 17, Address: "140 New Montgomery St"} ec.Subscribe("json_struct", func(p *person) { if !reflect.DeepEqual(p, me) { b.Fatalf("Did not receive the correct struct response") } ch <- true }) // resume benchmark b.StartTimer() for n := 0; n < b.N; n++ { ec.Publish("json_struct", me) if e := test.Wait(ch); e != nil { b.Fatal("Did not receive the message") } } }
// runMVCCGet first creates test data (and resets the benchmarking // timer). It then performs b.N MVCCGets. func runMVCCGet(emk engineMaker, numVersions, valueSize int, b *testing.B) { const overhead = 48 // Per key/value overhead (empirically determined) const targetSize = 512 << 20 // 512 MB // Adjust the number of keys so that each test has approximately the same // amount of data. numKeys := targetSize / ((overhead + valueSize) * (1 + (numVersions-1)/2)) eng, _ := setupMVCCData(emk, numVersions, numKeys, valueSize, b) defer eng.Close() b.SetBytes(int64(valueSize)) b.ResetTimer() keyBuf := append(make([]byte, 0, 64), []byte("key-")...) for i := 0; i < b.N; i++ { // Choose a random key to retrieve. keyIdx := rand.Int31n(int32(numKeys)) key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(keyIdx))) walltime := int64(5 * (rand.Int31n(int32(numVersions)) + 1)) ts := makeTS(walltime, 0) if v, _, err := MVCCGet(context.Background(), eng, key, ts, true, nil); err != nil { b.Fatalf("failed get: %s", err) } else if v == nil { b.Fatalf("failed get (key not found): %d@%d", keyIdx, walltime) } else if valueBytes, err := v.GetBytes(); err != nil { b.Fatal(err) } else if len(valueBytes) != valueSize { b.Fatalf("unexpected value size: %d", len(valueBytes)) } } b.StopTimer() }
func BenchmarkConnRoutingKey(b *testing.B) { const workers = 16 cluster := createCluster() cluster.NumConns = 1 cluster.PoolConfig.HostSelectionPolicy = TokenAwareHostPolicy(RoundRobinHostPolicy()) session := createSessionFromCluster(cluster, b) defer session.Close() if err := createTable(session, "CREATE TABLE IF NOT EXISTS routing_key_stress (id int primary key)"); err != nil { b.Fatal(err) } var seed uint64 writer := func(pb *testing.PB) { seed := atomic.AddUint64(&seed, 1) var i uint64 = 0 query := session.Query("insert into routing_key_stress (id) values (?)") for pb.Next() { if _, err := query.Bind(i * seed).GetRoutingKey(); err != nil { b.Error(err) return } i++ } } b.SetParallelism(workers) b.RunParallel(writer) }
func BenchmarkFirst16(b *testing.B) { const n = 5000 g := runtime.GOMAXPROCS(0) defer runtime.GOMAXPROCS(g) o := &Options{noClone: true} db, err := CreateTemp("_testdata", "temp", ".db", o) if err != nil { b.Fatal(err) } dbname := db.Name() defer func(n string) { db.Close() os.Remove(n) os.Remove(o._WAL) }(dbname) rng := fc() for i := 0; i < n; i++ { if err := db.Set(n2b(rng.Next()), n2b(rng.Next())); err != nil { b.Fatal(err) } } b.ResetTimer() for i := 0; i < b.N; i++ { db.First() } b.StopTimer() }
// Benchmarking raw database/sql. func BenchmarkAppendTxRawSQL(b *testing.B) { var err error var sess db.Database var tx *sql.Tx if sess, err = db.Open(Adapter, settings); err != nil { b.Fatal(err) } defer sess.Close() driver := sess.Driver().(*sql.DB) if tx, err = driver.Begin(); err != nil { b.Fatal(err) } if _, err = tx.Exec("TRUNCATE TABLE `artist`"); err != nil { b.Fatal(err) } b.ResetTimer() for i := 0; i < b.N; i++ { if _, err = tx.Exec("INSERT INTO `artist` (`name`) VALUES('Hayao Miyazaki')"); err != nil { b.Fatal(err) } } if err = tx.Commit(); err != nil { b.Fatal(err) } }
func BenchmarkMemStoreUnlimited(b *testing.B) { st, err := memstore.New(0) if err != nil { b.Fatal(err) } storetest.BenchmarkGCRAStore(b, st) }