Esempio n. 1
0
func BenchmarkGetCustomerAddresses(b *testing.B) {
	shopID := cart.InsertTestData()
	if shopID == nil {
		b.Error("failed to create a shop")
		b.Fail()
	}

	val := shopID.Hex()
	qs := make(url.Values, 0)
	qs.Add("shop", val)

	cust := cart.Customer{
		ShopId:    *shopID,
		FirstName: "Alex",
		LastName:  "Ninneman",
		Email:     time.Now().Format(time.RFC3339Nano) + "@gmail.com",
		Password:  "******",
	}
	if err := cust.Insert("http://www.example.com"); err != nil {
		b.Error(err.Error())
		b.Fail()
	}

	(&httprunner.BenchmarkOptions{
		Method:             "GET",
		Route:              "/shopify/customers/" + cust.Id.Hex() + "/addresses",
		ParameterizedRoute: "/shopify/customers/:id/addresses",
		Handler:            GetAddresses,
		QueryString:        &qs,
		Runs:               b.N,
	}).RequestBenchmark()
}
Esempio n. 2
0
func BenchmarkRemoteClient(t *testing.B) {
	t.SetParallelism(4)

	t.RunParallel(func(pb *testing.PB) {

		for pb.Next() {
			for i := 0; i < t.N; i++ {
				p := packet.NewPacket(1, []byte("echo"))
				tmp := clientManager.FindRemoteClients([]string{"a"}, func(groupid string, c *client.RemotingClient) bool {
					return false
				})

				_, err := tmp["a"][0].WriteAndGet(*p, 500*time.Millisecond)
				clientf.WriteFlow.Incr(1)
				if nil != err {
					t.Fail()
					log.Printf("WAIT RESPONSE FAIL|%s\n", err)
				} else {
					// log.Printf("WAIT RESPONSE SUCC|%s\n", string(resp.([]byte)))
				}
			}
		}

	})
}
Esempio n. 3
0
func BenchmarkToJSON2(b *testing.B) {
	var (
		vals = make([]bench3.Bench, b.N)
		res  = []byte{}
		err  error
	)

	for i := 0; i < b.N; i++ {
		vals[i] = bench3.NewBench("demo", 42, json.Marshal)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		res, err = vals[i].ToJSON()
		if err != nil {
			b.Logf("Failed test: %d with error: %q", i, err)
			b.Fail()
		}
	}

	b.StopTimer()

	byteEncoded = res
	runtime.GC()
}
Esempio n. 4
0
func benchAddRemove(amount int, b *testing.B) {
	g := New(16)
	if len(addRemoveList) > amount {
		addRemoveList = addRemoveList[:amount]
	}
	for n := 0; n < amount; n++ {
		if len(addRemoveList) == amount {
			break
		}
		addRemoveList = append(addRemoveList, random())
	}
	if len(addRemoveList) != amount {
		b.Log("len() reports", len(addRemoveList), "want", amount)
		b.Fail()
		return
	}
	b.ResetTimer()
	for n := 0; n < b.N; n++ {
		for _, s := range addRemoveList {
			g.Add(s)
			if !g.Remove(s) {
				b.Log("failed to remove")
				b.Fail()
			}
		}
	}
}
Esempio n. 5
0
// DEBUG: CPU1 - 45ns/op
// DEBUG: CPU2 - 0.75ns/op
func BenchmarkConvertXgb(b *testing.B) {
	b.StopTimer()
	diameter := int(math.Sqrt(float64(b.N)))
	if diameter > 5000 {
		diameter = 5000
	}
	r := image.Rect(0, 0, diameter, diameter)
	source := getrgba(r)
	target := &xgraphics.Image{
		X:      nil,
		Pixmap: 0,
		Pix:    make([]uint8, 4*r.Dx()*r.Dy()),
		Stride: 4 * r.Dx(),
		Rect:   r,
		Subimg: false,
	}
	b.StartTimer()

	convertRGBAtoXgb(target, source)

	b.StopTimer()
	if !compareImages(source, target) {
		b.Fail()
	}
	target.Destroy()
}
Esempio n. 6
0
func BenchmarkClosest1k(b *testing.B) {
	tree := New()

	n := 1000
	for i := 0; i < n; i++ {
		o := random()
		tree.Add(o)
	}
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		results := make(chan gfx.Boundable)
		tree.Closest(nil, results, nil)
		nResults := 0
		for {
			_, ok := <-results
			if !ok {
				break
			}
			nResults++
		}
		if len(results) != n {
			b.Log("results", nResults)
			b.Log("want", n)
			b.Fail()
		}
	}
}
Esempio n. 7
0
// Ideally should perform much better than both BenchmarkUpdateDumb and
// BenchmarkUpdateWorst.
func BenchmarkUpdateFast(b *testing.B) {
	objs := benchObjs
	for len(objs) < nUpdateObjects {
		objs = append(objs, random())
	}
	benchObjs = objs

	tree := New()
	for _, o := range objs {
		tree.Add(o)
	}

	b.ResetTimer()

	fail := 0
	success := 0
	for n := 0; n < b.N; n++ {
		oldIndex := n % len(objs)
		oldObj := objs[oldIndex]
		newObj := offset(oldObj.(gfx.Bounds))
		if !tree.Update(oldObj, newObj) {
			fail++
		} else {
			success++
		}
		objs[oldIndex] = newObj
	}
	if fail > 0 {
		b.Logf("Update failure ratio: fail=%d success=%d.", fail, success)
		b.Fail()
	}
}
Esempio n. 8
0
// 0.28 ns/op empty
// 32 ns/op with noop just method calls
// Each interop call costs ~30-45ns
func Benchmark_Logic(b *testing.B) {
	//data := make([]byte, 10)
	//var batch *Batch
	//buffer, _ := NewRingBuffer(SINGLE_WRITER, 16, 10)
	//defer buffer.Close()
	log.Printf("Bench: %d", b.N)
	for i := 0; i < b.N; i++ {
		buffer, _ := NewRingBuffer(64, 2)

		batch, _ := buffer.Claim(1)
		//batch.Entry(0).CopyFrom(GetData(10))
		//batch.CopyTo(0, )
		data := buffer.Entry(batch.SeqNum)
		//data := batch.Entry(0)
		if data[0] != uint8(10) {
			b.Fail()
		}
		//batch.Publish()
		buffer.Publish(batch)
		//batch, _ = buffer.Claim(1)
		//batch.Entries[0].CopyFrom(data)
		//batch.Publish()

		buffer.Close()
	}
}
Esempio n. 9
0
func BenchmarkMessages(b *testing.B) {
	numMessages := 10000

	adapter.count = numMessages

	var err error
	//b.ResetTimer()

	for i := 0; i < numMessages; i++ {
		go func() {
			//emsg := createTestBlock()
			emsg := createTestChaincodeEvent("0xffffffff", "event1")
			if err = producer.Send(emsg); err != nil {
				b.Fail()
				b.Logf("Error sending message %s", err)
			}
		}()
	}

	select {
	case <-adapter.notfy:
	case <-time.After(5 * time.Second):
		b.Fail()
		b.Logf("timed out on messge")
	}
}
Esempio n. 10
0
func BenchmarkQuery(t *testing.B) {

	log.Printf("BenchmarkQuery|Query|Start...")
	t.StopTimer()
	cleanSnapshot("./snapshot/")
	snapshot := NewMessageStore("./snapshot/", 1, 10, 1*time.Second, traverse)
	snapshot.Start()
	for j := 0; j < 20; j++ {
		d := []byte(fmt.Sprintf("%d|hello snapshot", j))
		cmd := NewCommand(-1, fmt.Sprint(j), d, nil)
		snapshot.Append(cmd)
	}

	time.Sleep(2 * time.Second)
	t.StartTimer()

	i := 0
	for ; i < t.N; i++ {
		id := int64(rand.Intn(20)) + 1
		_, err := snapshot.Query(id)
		if nil != err {
			log.Printf("Query|%s|%d\n", err, id)
			t.Fail()
			break
		}
	}

	t.StopTimer()
	snapshot.Destory()
	cleanSnapshot("./snapshot/")
	t.StartTimer()

}
Esempio n. 11
0
func BenchmarkRandomStr(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if len(RandomStr()) != 10 {
			b.Fail()
		}
	}
}
Esempio n. 12
0
func BenchmarkTermIndexSearch(b *testing.B) {
	ctx := BenchContext("TermIndexAdd")
	termSpace := 100
	numDocs := 1000
	numTermsPerDoc := 5
	ti := NewTermIndex()
	for i := 0; i < numDocs; i++ {
		id := "id" + strconv.Itoa(i)
		for j := 0; j < numTermsPerDoc; j++ {
			term := strconv.Itoa((i * j) % termSpace)
			ti.Add(ctx, term, id)
		}

	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		term1 := strconv.Itoa(i % termSpace)
		term2 := strconv.Itoa((i + 1) % termSpace)
		term3 := strconv.Itoa((i + 2) % termSpace)
		_, err := ti.Search(ctx, []string{term1, term2, term3})
		if err != nil {
			b.Fail()
		}
	}
}
Esempio n. 13
0
func BenchmarkReadWay(b *testing.B) {
	b.StopTimer()
	cache_dir, _ := ioutil.TempDir("", "imposm3_test")
	defer os.RemoveAll(cache_dir)

	cache, err := newWaysCache(cache_dir)
	if err != nil {
		b.Fatal()
	}
	defer cache.Close()

	way := &element.Way{}
	for i := 0; i < b.N; i++ {
		way.Id = int64(i)
		cache.PutWay(way)
	}

	b.StartTimer()
	for i := int64(0); i < int64(b.N); i++ {
		if coord, err := cache.GetWay(i); err != nil || coord.Id != i {
			b.Fail()
		}
	}

}
Esempio n. 14
0
func BenchmarkFetchNodeHourlyPubsize(b *testing.B) {
	b.StopTimer()
	lgr := newTestLogger(b)

	nsqdOpts := nsqd.NewOptions()
	nsqdOpts.TCPAddress = "127.0.0.1:0"
	nsqdOpts.HTTPAddress = "127.0.0.1:0"
	nsqdOpts.BroadcastAddress = "127.0.0.1"
	nsqdOpts.Logger = lgr

	_, _, nsqd1, nsqd1Srv := mustStartNSQD(nsqdOpts)
	b.Logf("nsqd started")

	time.Sleep(100 * time.Millisecond)

	var topicNames []string
	for i := 0; i < 1000; i++ {
		//create sample topics
		topicName := fmt.Sprintf("Topic-Benchmark%04d", i)
		nsqd1.GetTopic(topicName, 0)
		topicNames = append(topicNames, topicName)
		b.Logf("Topic %s created.", topicName)
	}

	type TopicHourlyPubsizeStat struct {
		TopicName      string `json:"topic_name"`
		TopicPartition string `json:"topic_partition"`
		HourlyPubsize  int64  `json:"hourly_pub_size"`
	}

	type NodeHourlyPubsizeStats struct {
		TopicHourlyPubsizeList []*TopicHourlyPubsizeStat `json:"node_hourly_pub_size_stats"`
	}

	b.StartTimer()
	for i := 0; i < b.N; i++ {
		endpoint := fmt.Sprintf("http://%s/message/historystats", nsqd1Srv.ctx.httpAddr.String())
		req, err := http.NewRequest("GET", endpoint, nil)
		if err != nil {
			b.Errorf("Fail to get message history from %s - %s", endpoint, err)
			b.Fail()
		}
		client := http.Client{}
		resp, err := client.Do(req)
		var nodeHourlyPubsizeStats NodeHourlyPubsizeStats
		body, _ := ioutil.ReadAll(resp.Body)
		json.Unmarshal(body, &nodeHourlyPubsizeStats)
		resp.Body.Close()
		b.Logf("Node topics hourly pub size list: %d", len(nodeHourlyPubsizeStats.TopicHourlyPubsizeList))
	}
	b.StopTimer()

	//cleanup
	for _, topicName := range topicNames {
		err := nsqd1.DeleteExistingTopic(topicName, 0)
		if err != nil {
			b.Logf("Fail to delete topic: %s", topicName)
		}
	}
}
Esempio n. 15
0
func BenchmarkQuadFilter(b *testing.B) {
	l, err := Open(small)
	if err != nil {
		return
	}
	l.BuildQuadTree()
	var points [rounds]int
	for i := 0; i < rounds; i++ {
		x, y := (l.MaxX-l.MinX)/2, (l.MaxY-l.MinY)/2
		xbuf := (l.MaxX - l.MinX) * 0.01 * float64(i)
		ybuf := (l.MaxY - l.MinY) * 0.01 * float64(i)
		l.SetFilter(x-xbuf, x+xbuf, y-ybuf, y+ybuf)
		f := 0
		for {
			_, err := l.GetNextPoint()
			if err != nil {
				break
			}
			f++
		}
		points[i] = f
	}
	for i := 1; i < rounds; i++ {
		if points[i-1] > points[i] {
			b.Fail()
		}
	}
}
func BenchmarkCarJSON(b *testing.B) {
	var carOriginal = GetCar(234234234)

	var destBytes []byte
	bufferE := bytes.NewBuffer(destBytes)
	e := json.NewEncoder(bufferE)

	e.Encode(carOriginal)
	destBytes = bufferE.Bytes()

	//fmt.Println("Bytes from JSON:",len(destBytes))

	b.ResetTimer()

	for i := 0; i < b.N; i++ {

		var carDecoded = Car{}

		reader := bytes.NewReader(destBytes)

		d := json.NewDecoder(reader)

		d.Decode(&carDecoded)

		if carDecoded.CarId <= 0 || len(carDecoded.CarName) < 1 {
			b.Fail()
			fmt.Println("id   = ", carDecoded.CarId)
			fmt.Println("name = ", carDecoded.CarName)
		}
	}
}
Esempio n. 17
0
func BenchmarkToJSONString2(b *testing.B) {
	var (
		vals = make([]bench2.Bench, b.N)
		res  = ""
		err  error
	)

	for i := 0; i < b.N; i++ {
		vals[i] = bench2.Bench{FieldA: "demo", FieldB: 42}
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		res, err = vals[i].ToJSONString2()
		if err != nil {
			b.Logf("Failed test: %d with error: %q", i, err)
			b.Fail()
		}
	}

	b.StopTimer()

	stringEncoded = res
	runtime.GC()
}
Esempio n. 18
0
func BenchmarkSinglePipe(b *testing.B) {
	for i := 0; i < b.N; i++ {
		pipeline := NewPipeline()
		p1 := pipeline.NewPipe(0)
		num := 1024
		n := 0
		go func() {
			for i := 0; i < num; i++ {
				pipeline.Add()
				if !p1.Do(func() {
					n++
					pipeline.Done()
				}) {
					return
				}
			}
			pipeline.Wait()
			pipeline.Close()
		}()
		p1.Process()
		if n != num {
			b.Fail()
		}
	}
}
Esempio n. 19
0
func BenchmarkTrieTree(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if tree.MatchValue(s).(bool) != true {
			b.Fail()
		}
	}
}
Esempio n. 20
0
func BenchmarkStoreObject(b *testing.B) {
	client := New("127.0.0.1:8087")
	err := client.Connect()
	if err != nil {
		b.FailNow()
	}

	for i := 0; i < b.N; i++ {
		bucket, err := client.Bucket("client_test.go")
		if err != nil {
			b.FailNow()
		}
		obj := bucket.New("abc", PW1, DW1)
		if obj == nil {
			b.FailNow()
		}
		obj.ContentType = "text/plain"
		obj.Data = []byte("some more data")
		err = obj.Store()
		if err != nil {
			b.Log(err)
			b.Fail()
		}
	}
}
Esempio n. 21
0
func benchmarkGet(valSize int, b *testing.B) {
	path, err := ioutil.TempDir("", "storetest_")
	if err != nil {
		b.Error(err)
		b.Fail()
		return
	}
	defer os.RemoveAll(path)

	var s Store
	s.Init(path)
	buf := make([]byte, valSize)

	nkeys := 100
	for i := 0; i < nkeys; i++ {
		key := []byte(fmt.Sprintf("key_%d", i))
		if err := s.SetOne(key, buf); err != nil {
			b.Error(err)
			return
		}
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		k := rand.Int() % nkeys
		key := []byte(fmt.Sprintf("key_%d", k))
		val, err := s.Get(key)
		if err != nil {
			b.Error(err)
		}
		if len(val) != valSize {
			b.Errorf("Value size expected: %d. Found: %d", valSize, len(val))
		}
	}
}
Esempio n. 22
0
func BenchmarkLoadModel(b *testing.B) {
	client := New("127.0.0.1:8087")
	err := client.Connect()
	if err != nil {
		b.FailNow()
	}
	// Create a new "DocumentModel" and save it
	doc := DMInclude{Name: "some name", Sub: SubStruct{Value: "some value"}}
	err = client.New("testmodel.go", "BenchModelKey", &doc)
	if err != nil {
		b.Log(err)
		b.FailNow()
	}
	err = doc.Save()
	if err != nil {
		b.Log(err)
		b.Fail()
	}

	for i := 0; i < b.N; i++ {
		err = client.Load("testmodel.go", "BenchModelKey", &doc, R1)
		if err != nil {
			b.Log(err)
			b.Fail()
		}
	}
}
Esempio n. 23
0
func BenchmarkRSAKeyGeneration(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_, err := GenerateRSAKey()
		if err != nil {
			b.Fail()
		}
	}
}
Esempio n. 24
0
func BenchmarkParser(b *testing.B) {
	for n := 0; n < b.N; n++ {
		x := Parse("<http://example/s> <http://example/p> \"object of some real\\tlength\"@en . # comment")
		if x.Obj != "object of some real\tlength" {
			b.Fail()
		}
	}
}
Esempio n. 25
0
func BenchmarkAppend(b *testing.B) {
	for n := 0; n < b.N; n++ {
		_, err := gorethink.Db("test").Table("benchmark_keys_list").Get(table2search).Field("voted").Append(uniuri.New()).Run(session)
		if err != nil {
			b.Log(err)
			b.Fail()
		}
	}
}
Esempio n. 26
0
func BenchmarkPrecomputedRSAKey(b *testing.B) {
	for i := 0; i < b.N; i++ {
		k, err := GenerateRSAKey()
		if err != nil {
			b.Fail()
		} else {
			k.Precompute()
		}
	}
}
Esempio n. 27
0
func BenchmarkReflect(b *testing.B) {
	initAdds()
	var r uintptr
	for i := 0; i < b.N; i++ {
		r = getProcAddress(h2, "LoadLibraryA")
	}
	if r != control {
		b.Fail()
	}
}
Esempio n. 28
0
func BenchmarkToAndFrom(b *testing.B) {
	benchmarks := []struct {
		k int
	}{
		{10},
		{100},
		{1000},
		{10000},
		{100000},
		{1000000},
		{10000000},
	}

	for _, bm := range benchmarks {
		for which := 0; which < 3; which++ {
			var name string
			if which == 0 {
				fmt.Println()
				name = "Flatb"
			} else if which == 1 {
				name = "Fixed"
			} else if which == 2 {
				name = "Proto"
			}

			b.Run(fmt.Sprintf("%s-%d", name, bm.k), func(b *testing.B) {
				uids := make([]uint64, bm.k)
				for i := 0; i < bm.k; i++ {
					uids[i] = uint64(rand.Int63())
				}

				var max, sz int
				b.ResetTimer()
				for i := 0; i < b.N; i++ {
					var err error
					if which == 0 {
						err, sz = ToAndFromFlat(uids)
					} else if which == 1 {
						err, sz = ToAndFromProtoAlt(uids)
					} else if which == 2 {
						err, sz = ToAndFromProto(uids)
					}
					if err != nil {
						b.Error(err)
						b.Fail()
					}
					if max < sz {
						max = sz
					}
					// runtime.GC() -- Actually makes FB looks worse.
				}
			})
		}
	}
}
Esempio n. 29
0
func BenchmarkSyscallBaseline(b *testing.B) {
	initAdds()
	var r uintptr
	for i := 0; i < b.N; i++ {
		t, _ := syscall.BytePtrFromString("LoadLibraryA")
		r, _, _ = a.Call(h, (uintptr)(unsafe.Pointer(t)))
	}
	if r != control {
		b.Fail()
	}
}
Esempio n. 30
0
func BenchmarkDelete(b *testing.B) {
	for n := 0; n < b.N; n++ {
		_, err := gorethink.Db("test").Table("benchmark_keys_list").Get(table2search).Field("voted").DeleteAt(
			gorethink.Expr(gorethink.Db("test").Table("benchmark_keys_list").Get(table2search).Field("voted").IndexesOf(key2find).AtIndex(0)),
		).Run(session)
		if err != nil {
			b.Log(err)
			b.Fail()
		}
	}
}