Exemple #1
1
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)
			}
		}
	}
}
Exemple #2
0
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 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])
		}
	}
}
Exemple #4
0
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()
	}
}
Exemple #5
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")
		}
	}

}
Exemple #6
0
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)
		}
	}
}
Exemple #7
0
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()
}
Exemple #8
0
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 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
}
Exemple #10
0
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 BenchmarkHelloRServer(b *testing.B) {
	test := func(k *kernel) {
		server := httptest.NewServer(k)
		defer server.Close()
		cli := &http.Client{Transport: &http.Transport{}}
		b.ResetTimer()
		defer b.StopTimer()
		for i := 0; i < b.N; i++ {
			body := bytes.NewBuffer([]byte(`{"name": "bigdatabob"}`))
			req, err := http.NewRequest("POST", server.URL, body)
			if err != nil {
				b.Errorf("could not create request: %v", err)
				return
			}
			req.Header.Set("Content-Type", "application/json")
			resp, err := cli.Do(req)
			if err != nil {
				b.Errorf("could not make a request: %v", err)
				return
			}
			if resp.StatusCode != http.StatusOK {
				b.Errorf("bad response from kernel: %s", resp.Status)
				return
			}
			resp.Body.Close()
		}
	}
	testDeployment(b, integration.RHello, test)
}
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")
		}
	}
}
Exemple #13
0
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)
}
Exemple #14
0
// runBenchmarkInsert benchmarks inserting count rows into a table.
func runBenchmarkInsert(b *testing.B, db *gosql.DB, count int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.insert`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.insert (k INT PRIMARY KEY)`); err != nil {
		b.Fatal(err)
	}
	defer func() {
		if _, err := db.Exec(`DROP TABLE bench.insert`); err != nil {
			b.Fatal(err)
		}
	}()

	b.ResetTimer()
	var buf bytes.Buffer
	val := 0
	for i := 0; i < b.N; i++ {
		buf.Reset()
		buf.WriteString(`INSERT INTO bench.insert VALUES `)
		for j := 0; j < count; j++ {
			if j > 0 {
				buf.WriteString(", ")
			}
			fmt.Fprintf(&buf, "(%d)", val)
			val++
		}
		if _, err := db.Exec(buf.String()); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()

}
Exemple #15
0
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)
}
Exemple #16
0
func BenchmarkReadInts(b *testing.B) {
	var ls Struct
	bsr := &byteSliceReader{}
	var r io.Reader = bsr
	b.SetBytes(2 * (1 + 2 + 4 + 8))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		bsr.remain = big
		Read(r, BigEndian, &ls.Int8)
		Read(r, BigEndian, &ls.Int16)
		Read(r, BigEndian, &ls.Int32)
		Read(r, BigEndian, &ls.Int64)
		Read(r, BigEndian, &ls.Uint8)
		Read(r, BigEndian, &ls.Uint16)
		Read(r, BigEndian, &ls.Uint32)
		Read(r, BigEndian, &ls.Uint64)
	}
	b.StopTimer()
	want := s
	want.Float32 = 0
	want.Float64 = 0
	want.Complex64 = 0
	want.Complex128 = 0
	want.Array = [4]uint8{0, 0, 0, 0}
	want.Bool = false
	want.BoolArray = [4]bool{false, false, false, false}
	if b.N > 0 && !reflect.DeepEqual(ls, want) {
		b.Fatalf("struct doesn't match:\ngot  %v;\nwant %v", ls, want)
	}
}
Exemple #17
0
// 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)
			}
		}
	}
}
Exemple #18
0
// runMVCCScan first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCScans in increments of numRows
// keys over all of the data in the Engine instance, restarting at
// the beginning of the keyspace, as many times as necessary.
func runMVCCScan(emk engineMaker, numRows, numVersions, valueSize int, b *testing.B) {
	// Use the same number of keys for all of the mvcc scan
	// benchmarks. Using a different number of keys per test gives
	// preferential treatment to tests with fewer keys. Note that the
	// datasets all fit in cache and the cache is pre-warmed.
	const numKeys = 100000

	eng, _ := setupMVCCData(emk, numVersions, numKeys, valueSize, b)
	defer eng.Close()

	b.SetBytes(int64(numRows * valueSize))
	b.ResetTimer()

	keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
	for i := 0; i < b.N; i++ {
		// Choose a random key to start scan.
		keyIdx := rand.Int31n(int32(numKeys - numRows))
		startKey := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(keyIdx)))
		walltime := int64(5 * (rand.Int31n(int32(numVersions)) + 1))
		ts := makeTS(walltime, 0)
		kvs, _, _, err := MVCCScan(context.Background(), eng, startKey, keyMax, int64(numRows), ts, true, nil)
		if err != nil {
			b.Fatalf("failed scan: %s", err)
		}
		if len(kvs) != numRows {
			b.Fatalf("failed to scan: %d != %d", len(kvs), numRows)
		}
	}

	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()
}
Exemple #20
0
// 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()
}
Exemple #21
0
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()

}
Exemple #22
0
func runMVCCConditionalPut(emk engineMaker, valueSize int, createFirst bool, b *testing.B) {
	rng, _ := randutil.NewPseudoRand()
	value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
	keyBuf := append(make([]byte, 0, 64), []byte("key-")...)

	eng := emk(b, fmt.Sprintf("cput_%d", valueSize))
	defer eng.Close()

	b.SetBytes(int64(valueSize))
	var expected *roachpb.Value
	if createFirst {
		for i := 0; i < b.N; i++ {
			key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
			ts := makeTS(timeutil.Now().UnixNano(), 0)
			if err := MVCCPut(context.Background(), eng, nil, key, ts, value, nil); err != nil {
				b.Fatalf("failed put: %s", err)
			}
		}
		expected = &value
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
		ts := makeTS(timeutil.Now().UnixNano(), 0)
		if err := MVCCConditionalPut(context.Background(), eng, nil, key, ts, value, expected, nil); err != nil {
			b.Fatalf("failed put: %s", err)
		}
	}

	b.StopTimer()
}
Exemple #23
0
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)
			}
		}
	})
}
Exemple #24
0
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()
	}
}
Exemple #25
0
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()
}
Exemple #26
0
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)
}
Exemple #27
0
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()
}
Exemple #28
0
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)
	}
}
Exemple #29
0
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()
}
Exemple #30
0
// 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()
}