func benchMatch(b *testing.B, re regexper, dos bool) { patterns := []string{`Hello World!`, `Hello Friend!`, `Hello 友達!`} for _, pat := range patterns { var rv bool if dos { rv = re.MatchString(pat) } else { rv = re.Match([]byte(pat)) } if !rv { b.Errorf("Expected to match, failed") return } } patterns = []string{`Goodbye World!`, `Hell no!`, `HelloWorld!`} for _, pat := range patterns { var rv bool if dos { rv = re.MatchString(pat) } else { rv = re.Match([]byte(pat)) } if rv { b.Errorf("Expected to NOT match, matched") return } } }
func BenchmarkContention(b *testing.B) { b.StopTimer() var procs = runtime.NumCPU() var origProcs = runtime.GOMAXPROCS(procs) var db = NewLogeDB(NewMemStore()) db.CreateType(NewTypeDef("counters", 1, &TestCounter{})) db.Transact(func(t *Transaction) { t.Set("counters", "contended", &TestCounter{Value: 0}) }, 0) b.StartTimer() var group sync.WaitGroup for i := 0; i < procs; i++ { group.Add(1) go LoopIncrement(db, "contended", &group, b.N) } group.Wait() b.StopTimer() db.Transact(func(t *Transaction) { var target = b.N * procs var counter = t.Read("counters", "contended").(*TestCounter) if counter.Value != uint32(target) { b.Errorf("Wrong count for counter: %d / %d", counter.Value, target) } }, 0) runtime.GOMAXPROCS(origProcs) }
func Benchmark__PubSubTwoConns(b *testing.B) { b.StopTimer() s := runBenchServer() c := createClientConn(b, "localhost", PERF_PORT) doDefaultConnect(b, c) bw := bufio.NewWriterSize(c, defaultSendBufSize) c2 := createClientConn(b, "localhost", PERF_PORT) doDefaultConnect(b, c2) sendProto(b, c2, "SUB foo 1\r\n") sendOp := []byte(fmt.Sprintf("PUB foo 2\r\nok\r\n")) ch := make(chan bool) expected := len("MSG foo 1 2\r\nok\r\n") * b.N go drainConnection(b, c2, ch, expected) b.StartTimer() for i := 0; i < b.N; i++ { bw.Write(sendOp) } err := bw.Flush() if err != nil { b.Errorf("Received error on FLUSH write: %v\n", err) } // Wait for connection to be drained <-ch b.StopTimer() c.Close() c2.Close() s.Shutdown() }
// same as above, but representing the most simple possible request // and handler. Notably: the handler does not call rw.Header(). func BenchmarkServerFakeConnWithKeepAliveLite(b *testing.B) { req := []byte(strings.Replace(`GET / HTTP/1.1 Host: golang.org `, "\n", "\r\n", -1)) res := []byte("Hello world!\n") conn := &rwTestConn{ Reader: &repeatReader{content: req, count: b.N}, Writer: ioutil.Discard, closec: make(chan bool, 1), } handled := 0 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { handled++ rw.Write(res) }) ln := &oneConnListener{conn: conn} go Serve(ln, handler) <-conn.closec if b.N != handled { b.Errorf("b.N=%d but handled %d", b.N, handled) } }
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) }
// BenchmarkSigVerify benchmarks how long it takes the secp256k1 curve to // verify signatures. func BenchmarkSigVerify(b *testing.B) { b.StopTimer() // Randomly generated keypair. // Private key: 9e0699c91ca1e3b7e3c9ba71eb71c89890872be97576010fe593fbf3fd57e66d pubKey := PublicKey{ Curve: S256(), X: fromHex("d2e670a19c6d753d1a6d8b20bd045df8a08fb162cf508956c31268c6d81ffdab"), Y: fromHex("ab65528eefbb8057aa85d597258a3fbd481a24633bc9b47a9aa045c91371de52"), } // Double sha256 of []byte{0x01, 0x02, 0x03, 0x04} msgHash := fromHex("8de472e2399610baaa7f84840547cd409434e31f5d3bd71e4d947f283874f9c0") sig := Signature{ R: fromHex("fef45d2892953aa5bbcdb057b5e98b208f1617a7498af7eb765574e29b5d9c2c"), S: fromHex("d47563f52aac6b04b55de236b7c515eb9311757db01e02cff079c3ca6efb063f"), } if !sig.Verify(msgHash.Bytes(), &pubKey) { b.Errorf("Signature failed to verify") return } b.StartTimer() for i := 0; i < b.N; i++ { sig.Verify(msgHash.Bytes(), &pubKey) } }
func benchmarkStoreRead(b *testing.B, store data.Store) { var n = 1000 benchmarkStoreInsert(b, store, n) b.ResetTimer() var users = store.Collection("users") for k := 0; k < b.N; k++ { var i = rand.Intn(n - 1) var name = fmt.Sprintf("user%d", i+1) var email = fmt.Sprintf("*****@*****.**", name) var usr User var err = users.Find(q.Or{ q.M{"id": name}, q.M{"name": name}, q.M{"email": name}, }).One(&usr) if err != nil { b.Errorf("find one failed with %v", err) b.FailNow() } err = users.Find(q.Or{ q.M{"id": email}, q.M{"name": email}, q.M{"email": email}, }).One(&usr) if err != nil { b.Errorf("find one failed with %v", err) b.FailNow() } } }
func BenchmarkRoundtripTxt(b *testing.B) { b.StopTimer() sample, min, max := initRoundtripBenchmarks() sampleString := string(sample) b.ReportAllocs() tb := (*TB)(b) db := tb.checkDB(sql.Open("mysql", dsn)) defer db.Close() b.StartTimer() var result string for i := 0; i < b.N; i++ { length := min + i if length > max { length = max } test := sampleString[0:length] rows := tb.checkRows(db.Query(`SELECT "` + test + `"`)) if !rows.Next() { rows.Close() b.Fatalf("crashed") } err := rows.Scan(&result) if err != nil { rows.Close() b.Fatalf("crashed") } if result != test { rows.Close() b.Errorf("mismatch") } rows.Close() } }
func BenchmarkRoundtripBin(b *testing.B) { b.StopTimer() sample, min, max := initRoundtripBenchmarks() b.ReportAllocs() tb := (*TB)(b) db := tb.checkDB(sql.Open("mysql", dsn)) defer db.Close() stmt := tb.checkStmt(db.Prepare("SELECT ?")) defer stmt.Close() b.StartTimer() var result sql.RawBytes for i := 0; i < b.N; i++ { length := min + i if length > max { length = max } test := sample[0:length] rows := tb.checkRows(stmt.Query(test)) if !rows.Next() { rows.Close() b.Fatalf("crashed") } err := rows.Scan(&result) if err != nil { rows.Close() b.Fatalf("crashed") } if !bytes.Equal(result, test) { rows.Close() b.Errorf("mismatch") } rows.Close() } }
func benchmarkScanner(b *testing.B, scanner osm.Scanner) (int, int, int) { var ( nodes int ways int relations int ) for scanner.Scan() { e := scanner.Element() if e.Node != nil { nodes++ } if e.Way != nil { ways++ } if e.Relation != nil { relations++ } } if err := scanner.Err(); err != nil { b.Errorf("scanner returned error: %v", err) } return nodes, ways, relations }
func BenchmarkRoundTrip(b *testing.B) { r1, s1 := Pipe() r2, s2 := Pipe() go func() { var m BenchMessage for { if err := r1.Receive(&m); err != nil { b.Fatalf("Error receiving BenchMessage: %s", err) } if err := s2.Send(&m); err != nil { b.Fatalf("Error sending BenchMessage: %s", err) } } }() var sm BenchMessage var rm BenchMessage for i := 0; i < b.N; i++ { sm.I = i if err := s1.Send(&sm); err != nil { b.Fatalf("Error sending bench message: %s", err) } if err := r2.Receive(&rm); err != nil { b.Fatalf("Error receiving bench message: %s", err) } if rm.I != sm.I { b.Errorf("Wrong int received: %d, expecting: %d", rm.I, sm.I) } } }
func BenchmarkClientFutureParallel(b *testing.B) { var err error client, err := Connect(server, opts) if err != nil { b.Errorf("No connection available") } _, err = client.Replace(spaceNo, tuple1) if err != nil { b.Errorf("No connection available") } b.RunParallel(func(pb *testing.PB) { exit := false for !exit { var fs [N]*Future var j int for j = 0; j < N && pb.Next(); j++ { fs[j] = client.SelectAsync(spaceNo, indexNo, offset, limit, iterator, key) } exit = j < N for j > 0 { j-- _, err = fs[j].Get() if err != nil { b.Error(err) } } } }) }
func BenchmarkBatch200RandomWritesParallel10(b *testing.B) { var term Term var data []map[string]interface{} b.SetParallelism(10) b.RunParallel(func(pb *testing.PB) { for pb.Next() { for is := 0; is < 200; is++ { r := rand.New(rand.NewSource(time.Now().UnixNano())) cid := map[string]interface{}{ "customer_id": strconv.FormatInt(r.Int63(), 10), } data = append(data, cid) } // Insert the new item into the database term = DB("benchmarks").Table("benchmarks").Insert(data) // Insert the new item into the database _, err := term.RunWrite(session, RunOpts{ MinBatchRows: 200, MaxBatchRows: 200, }) if err != nil { b.Errorf("insert failed [%s] ", err) } } }) }
func BenchmarkSequentialSoftWritesParallel10(b *testing.B) { var mu sync.Mutex si := 0 // p*GOMAXPROCS b.SetParallelism(10) b.RunParallel(func(pb *testing.PB) { for pb.Next() { mu.Lock() si++ mu.Unlock() data := map[string]interface{}{ "customer_id": si, } opts := InsertOpts{Durability: "soft"} // Insert the new item into the database _, err := Table("benchmarks").Insert(data, opts).RunWrite(session) if err != nil { b.Errorf("insert failed [%s] ", err) return } } }) }
func Benchmark10kGlobal(b *testing.B) { var remote []scanner.File for i := 0; i < 10000; i++ { remote = append(remote, scanner.File{Name: fmt.Sprintf("file%d", i), Version: 1000}) } m := NewSet() m.Replace(cid.LocalID+1, remote) var local []scanner.File for i := 0; i < 2000; i++ { local = append(local, scanner.File{Name: fmt.Sprintf("file%d", i), Version: 1000}) } for i := 2000; i < 10000; i++ { local = append(local, scanner.File{Name: fmt.Sprintf("file%d", i), Version: 980}) } m.ReplaceWithDelete(cid.LocalID, local) b.ResetTimer() for i := 0; i < b.N; i++ { fs := m.Global() if l := len(fs); l != 10000 { b.Errorf("wrong length %d != 10k", l) } } }
func BenchmarkClientFutureParallel(b *testing.B) { var err error conn, err := Connect(server, opts) if err != nil { b.Errorf("No connection available") } _, err = conn.Replace(spaceNo, []interface{}{uint(1), "hello", "world"}) if err != nil { b.Errorf("No connection available") } b.RunParallel(func(pb *testing.PB) { exit := false for !exit { var fs [N]*Future var j int for j = 0; j < N && pb.Next(); j++ { fs[j] = conn.SelectAsync(spaceNo, indexNo, 0, 1, IterAll, []interface{}{uint(1)}) } exit = j < N for j > 0 { j-- _, err = fs[j].Get() if err != nil { b.Error(err) } } } }) }
func Benchmark10kGlobal(b *testing.B) { var remote []protocol.FileInfo for i := 0; i < 10000; i++ { remote = append(remote, protocol.FileInfo{Name: fmt.Sprintf("file%d", i), Version: protocol.Vector{{ID: myID, Value: 1000}}}) } ldb, err := leveldb.Open(storage.NewMemStorage(), nil) if err != nil { b.Fatal(err) } m := db.NewFileSet("test", ldb) m.Replace(remoteDevice0, remote) var local []protocol.FileInfo for i := 0; i < 2000; i++ { local = append(local, protocol.FileInfo{Name: fmt.Sprintf("file%d", i), Version: protocol.Vector{{ID: myID, Value: 1000}}}) } for i := 2000; i < 10000; i++ { local = append(local, protocol.FileInfo{Name: fmt.Sprintf("file%d", i), Version: protocol.Vector{{1, 980}}}) } m.Replace(protocol.LocalDeviceID, local) b.ResetTimer() for i := 0; i < b.N; i++ { fs := globalList(m) if l := len(fs); l != 10000 { b.Errorf("wrong length %d != 10k", l) } } }
func BenchmarkDynamic(b *testing.B) { for i := 0; i < b.N; i++ { jsonObj, err := ParseJSON(jsonContent) if err != nil { b.Errorf("Error parsing json: %v\n", err) } FOSI := jsonObj.S("firstOutter", "secondInner") SOSI := jsonObj.S("secondOutter", "secondInner") SOTI := jsonObj.S("secondOutter", "thirdInner") if val := FOSI.S("numberType").Data().(float64); val != 12 { b.Errorf("Wrong value of FirstOutter.SecondInner.NumberType: %v\n", val) } expected := "hello world, first second" if val := FOSI.S("stringType").Data().(string); val != expected { b.Errorf("Wrong value of FirstOutter.SecondInner.StringType: %v\n", val) } if val := SOTI.S("numberType").Data().(float64); val != 23 { b.Errorf("Wrong value of SecondOutter.ThirdInner.NumberType: %v\n", val) } expected = "hello world, second second" if val := SOSI.S("stringType").Data().(string); val != expected { b.Errorf("Wrong value of SecondOutter.SecondInner.StringType: %v\n", val) } } }
func BenchmarkUnmarshalJSON2Tags(b *testing.B) { var bp client.BatchPoints data := []byte(` { "database": "foo", "retentionPolicy": "bar", "points": [ { "name": "cpu", "tags": { "host": "server01", "region": "us-east1" }, "time": 14244733039069373, "precision": "n", "fields": { "value": 4541770385657154000 } } ] } `) for i := 0; i < b.N; i++ { if err := json.Unmarshal(data, &bp); err != nil { b.Errorf("unable to unmarshal nanosecond data: %s", err.Error()) } b.SetBytes(int64(len(data))) } }
func BenchmarkRender(b *testing.B) { b.StopTimer() dir := createTestDir([]templateFile{ {"header.html", `header template`}, {"body.html", `body template`}, {"footer.html", `footer template`}, }) defer os.RemoveAll(dir) s := New(dir, false) err := s.RegisterLayout("alayout", "header", "footer", "", "") if err != nil { b.Fatal(err) } err = s.Register("body", "", "") if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { x, err := s.RenderToString("alayout", "body", nil) if err != nil { b.Fatal(err) } if x != "header templatebody templatefooter template" { b.Errorf("incorrect render: %q", x) } } }
func BenchmarkServerFakeConnWithKeepAlive(b *testing.B) { req := []byte(strings.Replace(`GET / HTTP/1.1 Host: golang.org Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 `, "\n", "\r\n", -1)) res := []byte("Hello world!\n") conn := &rwTestConn{ Reader: &repeatReader{content: req, count: b.N}, Writer: ioutil.Discard, closec: make(chan bool, 1), } handled := 0 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { handled++ rw.Header().Set("Content-Type", "text/html; charset=utf-8") rw.Write(res) }) ln := &oneConnListener{conn: conn} go Serve(ln, handler) <-conn.closec if b.N != handled { b.Errorf("b.N=%d but handled %d", b.N, handled) } }
// Benchmark_WithValidateBaseUrl-4 3000 489089 ns/op 188333 B/op 272 allocs/op => with debug enabled // Benchmark_WithValidateBaseUrl-4 200000 8925 ns/op 2924 B/op 49 allocs/op => no debug func Benchmark_WithValidateBaseUrl(b *testing.B) { // todo: there is room for optimization with disabled debugging. too many allocs store.PkgLog.SetLevel(log.StdLevelInfo) req, err := http.NewRequest(httputils.MethodGet, "https://corestore.io/customer/comments/view?id=1916#tab=ratings", nil) if err != nil { b.Fatal(err) } finalHandler := store.WithValidateBaseURL(middlewareConfigReader)(ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { return errors.New("This handler should not be called!") })) want := "https://www.corestore.io/customer/comments/view?id=1916#tab=ratings" rec := httptest.NewRecorder() b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { if err := finalHandler.ServeHTTPContext(middlewareCtxStoreService, rec, req); err != nil { b.Error(err) } if rec.HeaderMap.Get("Location") != want { b.Errorf("Have: %s\nWant: %s", rec.HeaderMap.Get("Location"), want) } rec.HeaderMap = nil } }
func BenchmarkBothSerial(b *testing.B) { serverAddr, err := setupBenchServer() require.NoError(b, err, "setupBenchServer failed") opts := testutils.NewOpts().SetFramePool(tchannel.NewSyncFramePool()) clientCh := testutils.NewClient(b, opts) for _, addr := range serverAddr { clientCh.Peers().Add(addr) } thriftClient := thrift.NewClient(clientCh, "bench-server", nil) client := gen.NewTChanSecondServiceClient(thriftClient) ctx, cancel := thrift.NewContext(10 * time.Millisecond) client.Echo(ctx, "make connection") cancel() b.ResetTimer() for i := 0; i < b.N; i++ { ctx, cancel := thrift.NewContext(10 * time.Millisecond) defer cancel() _, err := client.Echo(ctx, "hello world") if err != nil { b.Errorf("Echo failed: %v", err) } } }
func Benchmark10kHaveFullList(b *testing.B) { var remote []protocol.FileInfo for i := 0; i < 10000; i++ { remote = append(remote, protocol.FileInfo{Name: fmt.Sprintf("file%d", i), Version: 1000}) } db, err := leveldb.Open(storage.NewMemStorage(), nil) if err != nil { b.Fatal(err) } m := files.NewSet("test", db) m.Replace(remoteNode0, remote) var local []protocol.FileInfo for i := 0; i < 2000; i++ { local = append(local, protocol.FileInfo{Name: fmt.Sprintf("file%d", i), Version: 1000}) } for i := 2000; i < 10000; i++ { local = append(local, protocol.FileInfo{Name: fmt.Sprintf("file%d", i), Version: 980}) } m.ReplaceWithDelete(protocol.LocalNodeID, local) b.ResetTimer() for i := 0; i < b.N; i++ { fs := haveList(m, protocol.LocalNodeID) if l := len(fs); l != 10000 { b.Errorf("wrong length %d != 10k", l) } } }
func BenchmarkHTTPSplitResponse(b *testing.B) { data1 := []byte("HTTP/1.1 200 OK\r\n" + "Date: Tue, 14 Aug 2012 22:31:45 GMT\r\n" + "Expires: -1\r\n" + "Cache-Control: private, max-age=0\r\n" + "Content-Type: text/html; charset=UTF-8\r\n") data2 := []byte("Content-Encoding: gzip\r\n" + "Server: gws\r\n" + "Content-Length: 0\r\n" + "X-XSS-Protection: 1; mode=block\r\n" + "X-Frame-Options: SAMEORIGIN\r\n" + "\r\n") http := httpModForTests() parser := newParser(&http.parserConfig) for i := 0; i < b.N; i++ { stream := &stream{data: data1, message: new(message)} ok, complete := parser.parse(stream, 0) if !ok || complete { b.Errorf("parse failure. Expected message to be incomplete, but no parse failures") } stream.data = append(stream.data, data2...) ok, complete = parser.parse(stream, 0) if !ok || !complete { b.Errorf("failed to parse message") } } }
func benchmarkServeAsync(b *testing.B, srv, cli *Conn) { dest := srv.Names()[0] srv.Export(server{}, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test") obj := cli.Object(dest, "/org/guelfey/DBus/Test") c := make(chan *Call, 50) done := make(chan struct{}) go func() { for i := 0; i < b.N; i++ { v := <-c if v.Err != nil { b.Fatal(v.Err) } i, r := v.Args[0].(int64), v.Body[0].(int64) if 2*i != r { b.Errorf("got %d, wanted %d", r, 2*i) } } close(done) }() b.StartTimer() for i := 0; i < b.N; i++ { obj.Go("org.guelfey.DBus.Test.Double", 0, c, int64(i)) } <-done }
func bench(b *testing.B, size int, algo func(Interface), name string) { b.StopTimer() data := make(intPairs, size) x := ^uint32(0) for i := 0; i < b.N; i++ { for n := size - 3; n <= size+3; n++ { for i := 0; i < len(data); i++ { x += x x ^= 1 if int32(x) < 0 { x ^= 0x88888eef } data[i].a = int(x % uint32(n/5)) } data.initB() b.StartTimer() algo(data) b.StopTimer() if !IsSorted(data) { b.Errorf("%s did not sort %d ints", name, n) } if name == "Stable" && !data.inOrder() { b.Errorf("%s unstable on %d ints", name, n) } } } }
func BenchmarkCallAsync(b *testing.B) { b.StopTimer() bus, err := SessionBus() if err != nil { b.Fatal(err) } name := bus.Names()[0] obj := bus.BusObject() c := make(chan *Call, 50) done := make(chan struct{}) go func() { for i := 0; i < b.N; i++ { v := <-c if v.Err != nil { b.Error(v.Err) } s := v.Body[0].(string) if s != name { b.Errorf("got %s, wanted %s", s, name) } } close(done) }() b.StartTimer() for i := 0; i < b.N; i++ { obj.Go("org.freedesktop.DBus.GetNameOwner", 0, c, name) } <-done }
func BenchmarkExist(b *testing.B) { b.StopTimer() var d Interface if opt == "slice" { d = newMapToSlice() } else { d = newMapToMap() } k := "A" for _, v := range testVals { d.set(k, v) } // to make it not biased towards data structures // with an order, such as slice. ix := rand.Perm(testN) b.StartTimer() b.ReportAllocs() for _, idx := range ix { if !d.exist(k, testVals[idx]) { b.Errorf("%s should have existed!", testVals[idx]) } } }
func BenchmarkHbasePut(b *testing.B) { var ( err error h = NewHBaseClient() m = &meta.Needle{} t int64 ) ch := make(chan int64, 1000000) if err = Init("172.16.13.90:9090", 5*time.Second, 200, 200); err != nil { b.Errorf("Init failed") b.FailNow() } for j := 0; j < 1000000; j++ { k := int64(time.Now().UnixNano()) ch <- k } b.ResetTimer() b.SetParallelism(8) b.RunParallel(func(pb *testing.PB) { for pb.Next() { t = <-ch m.Key = t if err = h.Put(m); err != nil { continue } } }) }