func BenchmarkCacheComplete(b *testing.B) { b.StopTimer() paths := DefaultPaths() if len(paths) == 0 { b.Skip("No default paths available") } tests := []string{"mscorlib.dll", "System.dll"} c := Cache{paths: paths} for _, test := range tests { if _, err := c.Load(test); err != nil { b.Error(err) } } tests2 := []content.Type{ content.Type{Name: content.FullyQualifiedName{Absolute: "net://type/System.String"}}, } b.StartTimer() for i := 0; i < b.N; i++ { for _, test := range tests2 { if _, err := c.Complete(&test); err != nil { b.Error(err) } } } }
func BenchmarkUnma(b *testing.B) { popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) total := 0 data := new(bytes.Buffer) enc := gob.NewEncoder(data) dec := gob.NewDecoder(data) b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() p := NewPopulatedPreAccept(popr) enc.Encode(p) total += len(data.Bytes()) msg := &PreAccept{} b.StartTimer() dec.Decode(&msg) } b.SetBytes(int64(total / b.N)) }
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 BenchmarkTopicToChannelPut(b *testing.B) { b.StopTimer() log.SetOutput(ioutil.Discard) defer log.SetOutput(os.Stdout) topicName := "bench_topic_to_channel_put" + strconv.Itoa(b.N) channelName := "bench" options := NewNSQDOptions() options.MemQueueSize = int64(b.N) _, _, nsqd := mustStartNSQD(options) defer nsqd.Exit() channel := nsqd.GetTopic(topicName).GetChannel(channelName) b.StartTimer() for i := 0; i <= b.N; i++ { topic := nsqd.GetTopic(topicName) msg := nsq.NewMessage(<-nsqd.idChan, []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaa")) topic.PutMessage(msg) } for { if len(channel.memoryMsgChan) == b.N { break } runtime.Gosched() } }
// ReadWrite does read and write in parallel. // qRead is num goroutines for reading. // qWrite is num goroutines for writing. // Assume n divisible by (qRead + qWrite). func ReadWrite(n, qRead, qWrite int, newFunc func() HashMap, b *testing.B) { q := qRead + qWrite check(n, q) work := intPairArray(n) b.StartTimer() for i := 0; i < b.N; i++ { // N reps. h := newFunc() var wg sync.WaitGroup for j := 0; j < qRead; j++ { // Read goroutines. wg.Add(1) go func(j int) { defer wg.Done() start, end := workRange(n, q, j) for k := start; k < end; k++ { h.Get(work[k].Key) } }(j) } for j := qRead; j < q; j++ { // Write goroutines. wg.Add(1) go func(j int) { defer wg.Done() start, end := workRange(n, q, j) for k := start; k < end; k++ { h.Put(work[k].Key, work[k].Val) } }(j) } wg.Wait() } }
func benchmarkClientServerParallel(b *testing.B, parallelism int) { b.ReportAllocs() b.StopTimer() handler, err := NewHandler(func(in Ping, out *Pong) error { if in.Data != "ping" { b.Fatalf("expected ping, got %q", in.Data) } out.Data = "pong" return nil }) if err != nil { b.Fatalf("NewHandler: %v", err) } s := npctest.NewServer(handler) defer s.Close() c := NewClient([]string{s.Listener.Addr().String()}) defer c.Close() b.SetParallelism(parallelism) b.StartTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { var pong Pong err = c.Call(Ping{"ping"}, &pong) if err != nil { b.Fatalf("Call: %v", err) } if pong.Data != "pong" { b.Fatalf("expected pong, got %q", pong.Data) } } }) }
func BenchmarkIndex1024(b *testing.B) { i := ChecksumIndex{} i.weakChecksumLookup = make([]map[uint32]StrongChecksumList, 256) for x := 0; x < 1024; x++ { w := rand.Uint32() if i.weakChecksumLookup[w&255] == nil { i.weakChecksumLookup[w&255] = make(map[uint32]StrongChecksumList) } i.weakChecksumLookup[w&255][w] = append( i.weakChecksumLookup[w&255][w], chunks.ChunkChecksum{}, ) } b.SetBytes(1) b.StartTimer() for x := 0; x < b.N; x++ { i.FindWeakChecksum2(T) } b.StopTimer() }
func BenchmarkWriteBoom(b *testing.B) { if *file == "" { b.Skip("no file specified") } b.StopTimer() br, err := boom.OpenBAM(*file) if err != nil { b.Fatalf("Open failed: %v", err) } f, err := os.OpenFile("/dev/null", os.O_APPEND|os.O_RDWR, 0666) if err != nil { b.Fatalf("Open failed: %v", err) } bw, err := boom.OpenBAMFile(f, "bw", br.Header()) if err != nil { b.Fatalf("NewWriter failed: %v", err) } r, _, err := br.Read() if err != nil { b.Fatalf("Read failed: %v", err) } b.StartTimer() for i := 0; i < b.N; i++ { _, err = bw.Write(r) if err != nil { b.Fatalf("Write failed: %v", err) } } br.Close() f.Close() }
func doBenchmarkFind(b *testing.B) { b.StopTimer() bas := new(basic) bas.Name = "Basic" bas.State = 3 mg, _ := GetMigration() mg.DropTable(bas) mg.CreateTableIfNotExists(bas) q, _ := GetQbs() q.Save(bas) closeMigrationAndQbs(mg, q) b.StartTimer() for i := 0; i < b.N; i++ { ba := new(basic) ba.Id = 1 q, _ = GetQbs() err := q.Find(ba) if err != nil { panic(err) } q.Close() } b.StopTimer() runtime.GC() stats := new(runtime.MemStats) runtime.ReadMemStats(stats) fmt.Printf("alloc:%d, total:%d\n", stats.Alloc, stats.TotalAlloc) }
func doBenchmarkDbQuery(b *testing.B) { b.StopTimer() bas := new(basic) bas.Name = "Basic" bas.State = 3 mg, _ := GetMigration() mg.DropTable(bas) mg.CreateTableIfNotExists(bas) q, _ := GetQbs() q.Save(bas) closeMigrationAndQbs(mg, q) b.StartTimer() db, _ := sql.Open(driver, driverSource) query := q.Dialect.substituteMarkers("SELECT * FROM basic WHERE id = ?") for i := 0; i < b.N; i++ { ba := new(basic) rows, err := db.Query(query, 1) if err != nil { panic(err) } rows.Next() err = rows.Scan(&ba.Id, &ba.Name, &ba.State) if err != nil { panic(err) } rows.Close() } db.Close() b.StopTimer() runtime.GC() stats := new(runtime.MemStats) runtime.ReadMemStats(stats) fmt.Printf("alloc:%d, total:%d\n", stats.Alloc, stats.TotalAlloc) }
func BenchmarkRoute2DB1(b *testing.B) { b.StopTimer() var sp Sparrow sp.Initialize(nil) b.StartTimer() for i := 0; i < b.N; i++ { rc, err := sp.Route2DB("db", "table", "user_id", "id0041", false, false) if err != nil { b.Error(err) } if rc == nil || rc.DBNode == nil || len(rc.DBName) <= 0 || len(rc.TableName) <= 0 { b.Errorf("dbatom:%v, dbname: %v, tablename:%v\n", rc.DBNode, rc.DBName, rc.TableName) } if rc.DBNode.IsMaster { b.Errorf("dbname: %s, tablename: %d, should not be master.", rc.DBNode.Ip, rc.DBNode.Port) } if !rc.DBNode.DBEnable { b.Errorf("dbname: %s, tablename: %d, disable.", rc.DBNode.Ip, rc.DBNode.Port) } } }
// Benchmark sealing a 1MiB message. func BenchmarkSealLongMsg(b *testing.B) { b.StopTimer() msg, err := ioutil.ReadFile("testdata/long.dat") if err != nil { fmt.Println("secretbox: failed to read short test message") fmt.Printf("%v\n", err) b.FailNow() } longMsg = msg b.StartTimer() for i := 0; i < b.N; i++ { _, ok := Seal(msg, testKey) if !ok { fmt.Println("secretbox: failed to seal message") b.FailNow() } b.SetBytes(int64(len(msg))) } b.StopTimer() var ok bool longBox, ok = Seal(msg, testKey) if !ok { fmt.Println("secretbox: failed to seal message") b.FailNow() } }
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 RunBenchmark(b *testing.B, suite string, name string, specificLogic func(b *testing.B, doc *XmlDocument)) { b.StopTimer() // defer CheckXmlMemoryLeaks(b) input, _, error := getTestData(filepath.Join("tests", suite, name)) if len(error) > 0 { panic(fmt.Sprintf("Error gathering test data for %v:\n%v\n", name, error)) } doc, err := parseInput(input) if err != nil { panic("Error:" + err.Error()) } b.StartTimer() if specificLogic != nil { specificLogic(b, doc) } doc.Free() // println("----------- END OF BENCHMARK -----------") }
func BenchmarkClientServer(b *testing.B) { b.StopTimer() ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { fmt.Fprintf(rw, "Hello world.\n") })) defer ts.Close() b.StartTimer() for i := 0; i < b.N; i++ { res, err := http.Get(ts.URL) if err != nil { b.Fatal("Get:", err) } all, err := ioutil.ReadAll(res.Body) if err != nil { b.Fatal("ReadAll:", err) } body := string(all) if body != "Hello world.\n" { b.Fatal("Got body:", body) } } b.StopTimer() }
// BenchmarkParseProtoGzip is like BenchmarkParseProto above, but parses gzipped // protobuf format. func BenchmarkParseProtoGzip(b *testing.B) { b.StopTimer() data, err := ioutil.ReadFile("testdata/protobuf.gz") if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { family := &dto.MetricFamily{} in, err := gzip.NewReader(bytes.NewReader(data)) if err != nil { b.Fatal(err) } for { family.Reset() if _, err := pbutil.ReadDelimited(in, family); err != nil { if err == io.EOF { break } b.Fatal(err) } } } }
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 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 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() }
func BenchmarkDagmodWrite(b *testing.B) { b.StopTimer() dserv, pins := getMockDagServ(b) _, n := getNode(b, dserv, 0, pins) ctx, cancel := context.WithCancel(context.Background()) defer cancel() wrsize := 4096 dagmod, err := NewDagModifier(ctx, n, dserv, pins, sizeSplitterGen(512)) if err != nil { b.Fatal(err) } buf := make([]byte, b.N*wrsize) u.NewTimeSeededRand().Read(buf) b.StartTimer() b.SetBytes(int64(wrsize)) for i := 0; i < b.N; i++ { n, err := dagmod.Write(buf[i*wrsize : (i+1)*wrsize]) if err != nil { b.Fatal(err) } if n != wrsize { b.Fatal("Wrote bad size") } } }
func BenchmarkClientServer(b *testing.B) { b.ReportAllocs() b.StopTimer() handler, err := NewHandler(func(in Ping, out *Pong) error { if in.Data != "ping" { b.Fatalf("expected ping, got %q", in.Data) } out.Data = "pong" return nil }) if err != nil { b.Fatalf("NewHandler: %v", err) } s := npctest.NewServer(handler) defer s.Close() c := NewClient([]string{s.Listener.Addr().String()}) defer c.Close() b.StartTimer() for i := 0; i < b.N; i++ { var pong Pong err = c.Call(Ping{"ping"}, &pong) if err != nil { b.Fatalf("Call: %v", err) } if pong.Data != "pong" { b.Fatalf("expected pong, got %q", pong.Data) } } }
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 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") } } }
func BenchmarkSecretConnection(b *testing.B) { b.StopTimer() fooSecConn, barSecConn := makeSecretConnPair(b) fooWriteText := RandStr(dataMaxSize) // Consume reads from bar's reader go func() { readBuffer := make([]byte, dataMaxSize) for { _, err := barSecConn.Read(readBuffer) if err == io.EOF { return } else if err != nil { b.Fatalf("Failed to read from barSecConn: %v", err) } } }() b.StartTimer() for i := 0; i < b.N; i++ { _, err := fooSecConn.Write([]byte(fooWriteText)) if err != nil { b.Fatalf("Failed to write to fooSecConn: %v", err) } } b.StopTimer() fooSecConn.Close() //barSecConn.Close() race condition }
func Benchmark_PubFourQueueSub(b *testing.B) { b.StopTimer() s := runBenchServer() c := createClientConn(b, "localhost", PERF_PORT) doDefaultConnect(b, c) sendProto(b, c, "SUB foo group1 1\r\n") sendProto(b, c, "SUB foo group1 2\r\n") sendProto(b, c, "SUB foo group1 3\r\n") sendProto(b, c, "SUB foo group1 4\r\n") bw := bufio.NewWriterSize(c, defaultSendBufSize) 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, c, ch, expected) b.StartTimer() for i := 0; i < b.N; i++ { _, err := bw.Write(sendOp) if err != nil { b.Fatalf("Received error on PUB write: %v\n", err) } } err := bw.Flush() if err != nil { b.Fatalf("Received error on FLUSH write: %v\n", err) } // Wait for connection to be drained <-ch b.StopTimer() c.Close() s.Shutdown() }
func runMVCCDeleteRange(emk engineMaker, valueBytes int, b *testing.B) { // 512 KB ranges so the benchmark doesn't take forever const rangeBytes = 512 * 1024 const overhead = 48 // Per key/value overhead (empirically determined) numKeys := rangeBytes / (overhead + valueBytes) eng, dir := setupMVCCData(emk, 1, numKeys, valueBytes, b) defer eng.Close() b.SetBytes(rangeBytes) b.StopTimer() b.ResetTimer() for i := 0; i < b.N; i++ { locDirty := dir + "_dirty" if err := os.RemoveAll(locDirty); err != nil { b.Fatal(err) } if err := shutil.CopyTree(dir, locDirty, nil); err != nil { b.Fatal(err) } dupEng := emk(b, locDirty) b.StartTimer() _, _, _, err := MVCCDeleteRange(context.Background(), dupEng, &enginepb.MVCCStats{}, roachpb.KeyMin, roachpb.KeyMax, math.MaxInt64, hlc.MaxTimestamp, nil, false) if err != nil { b.Fatal(err) } b.StopTimer() dupEng.Close() } }
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 BenchmarkEncode(b *testing.B) { b.StopTimer() bo := image.Rect(0, 0, 640, 480) rnd := rand.New(rand.NewSource(123)) // Restrict to a 256-color paletted image to avoid quantization path. palette := make(color.Palette, 256) for i := range palette { palette[i] = color.RGBA{ uint8(rnd.Intn(256)), uint8(rnd.Intn(256)), uint8(rnd.Intn(256)), 255, } } img := image.NewPaletted(image.Rect(0, 0, 640, 480), palette) for y := bo.Min.Y; y < bo.Max.Y; y++ { for x := bo.Min.X; x < bo.Max.X; x++ { img.Set(x, y, palette[rnd.Intn(256)]) } } b.SetBytes(640 * 480 * 4) b.StartTimer() for i := 0; i < b.N; i++ { Encode(ioutil.Discard, img, nil) } }
func benchCore(b *testing.B, hostAndPort string) { b.StopTimer() client, err := DialTimeout(hostAndPort, 1*time.Second) if err != nil { b.Fatalf("Failed to connect: %v", err) } jobBody := []byte("testing") b.StartTimer() for i := 0; i < b.N; i += 1 { _, _, err := client.Put(0, 0, 0, jobBody) if err != nil { b.Fatalf("Failed to Put: %v", err) } } for i := 0; i < b.N; i += 1 { _, _, err := client.Reserve() if err != nil { b.Fatalf("Failed to Reserve: %v", err) } } client.Quit() }
func Benchmark1DoozerConClientSet(b *testing.B) { var ( l = mustListen() a = l.Addr().String() u = mustListenUDP(a) st = store.New(store.DefaultInitialRev) ) defer l.Close() defer u.Close() b.StopTimer() go Main("a", "X", "", "", "", nil, u, l, nil, 1e9, 2e9, 3e9, 101, st) cl := dial(l.Addr().String()) c := make(chan bool, b.N) b.StartTimer() for i := 0; i < b.N; i++ { go func() { cl.Set("/test", store.Clobber, nil) c <- true }() } for i := 0; i < b.N; i++ { <-c } }