// WARNING: The benchmark run here is hardcoded (in two places)
// You must recompile to change the benchmark
552601
func benchmark32s(n int) {
	//var hashes = make(Uint32Slice, n)
	const nbytes = 16384 // fix
	bs := make([]byte, nbytes, nbytes)
	bs = bs[:]
	//fp20 := make([]byte, 20, 20)
	Hf2 = "nullhash"
	for _, ksiz := range keySizes {
		if ksiz == 512 {
			n = n / 10
		}
		bs = bs[:ksiz]
		//hashes = make(Uint32Slice, n, n)
		//hashes = hashes[:]
		//fmt.Printf("ksiz=%d, len(bs)=%d\n", ksiz, len(bs))
		pn := hrff.Int64{int64(n), ""}
		ps := hrff.Int64{int64(n * ksiz), "B"}
		//fmt.Printf("benchmark32s: gen n=%d, n=%h, keySize=%d, size=%h\n", n, pn, ksiz, ps)
		if false {
			_ = gomap.Hash64(bs, 0)
			_ = aeshash.Hash(bs, 0)
		}
		start, stop := time.Now(), time.Now()
		switch ksiz {
		case 4:
			start = time.Now()
			for i := 0; i < n; i++ {
				_ = aeshash.Hash(bs, 0)
				// sha1160.Reset()
				// sha1160.Write(bs)
				// fp20 = fp20[0:0]
				// fp20 = sha1160.Sum(fp20)
				// _ = uint64(fp20[0])<<56 | uint64(fp20[1])<<48 | uint64(fp20[2])<<40 | uint64(fp20[3])<<32 |
				// 	uint64(fp20[4])<<24 | uint64(fp20[5])<<16 | uint64(fp20[6])<<8  | uint64(fp20[7])<<0
				//k224.Reset()
				//k224.Write(bs)
				//_ = k224.Sum(nil)
				//bs[0], bs[1], bs[2], bs[3] = byte(i), byte(i>>8), byte(i>>16), byte(i>>24)
				//_, _ = jenkins.Jenkins364(bs, 0, 0, 0)
				//_ = jenkins.Hash232(bs, 0)
				//_, _ = jenkins.Jenkins364(bs, 0, 0, 0)
				//_ = gomap.Hash64(bs, 0)
				//_ =  nhf64.Hash64S(bs, 0) // chnage below too
				//nh.Reset()
				//nh.Write(bs)
				//_ = nh.Sum64()
				//Hashf(bs, 0)
				//_ = siphash.Hash(0, 0, bs)
				//hashes[i] = h
				//fmt.Printf("i=%d, 0x%08x, h=0x%08x\n", i, i, h)
				//hashes[i] = h
				//fmt.Printf("i=%d, 0x%08x, h=0x%08x\n", i, i, h)
			}
			stop = time.Now()
		default:
			start = time.Now()
			for i := 0; i < n; i++ {
				// sha1160.Reset()
				// sha1160.Write(bs)
				// fp20 = fp20[0:0]
				// fp20 = sha1160.Sum(fp20)
				// _ = uint64(fp20[0])<<56 | uint64(fp20[1])<<48 | uint64(fp20[2])<<40 | uint64(fp20[3])<<32 |
				// 	uint64(fp20[4])<<24 | uint64(fp20[5])<<16 | uint64(fp20[6])<<8  | uint64(fp20[7])<<0
				_ = aeshash.Hash(bs, 0)
				//k224.Reset()
				//k224.Write(bs)
				//_ = k224.Sum(nil)
				//bs[0], bs[1], bs[2], bs[3], bs[4], bs[5], bs[6], bs[7] = byte(i), byte(i>>8), byte(i>>16), byte(i>>24), byte(i>>32), byte(i>>40), byte(i>>48), byte(i>>56)
				//_, _ = jenkins.Jenkins364(bs, 0, 0, 0)
				//_ = aeshash.Hash(bs, 0)
				//_ = gomap.Hash64(bs, 0)
				//_ = siphash.Hash(0, 0, bs)
				//_ =  nhf64.Hash64S(bs, 0)
				//nh.Reset()
				//nh.Write(bs)
				//_ = nh.Sum64()
				//Hashf(bs, 0)
			}
			stop = time.Now()
		}
		d := tdiff(start, stop)
		hsec := hrff.Float64{(float64(n) / d.Seconds()), "hashes/sec"}
		bsec := hrff.Float64{(float64(n) * float64(ksiz) / d.Seconds()), "B/sec"}
		//fmt.Printf("benchmark32s: %h\n", hsec)
		//fmt.Printf("benchmark32s: %.2h\n\n", bsec)
		fmt.Printf("\tksize=%d, n=%h, size=%h, %h, %.1h, time=%v\n", ksiz, pn, ps, hsec, bsec, d)
	}
	return

	fmt.Printf("benchmark32s: sort n=%d\n", n)
	//hashes.Sort()
	/*
		for i := 0; i < n; i++ {
			fmt.Printf("i=%d, 0x%08x, h=0x%08x\n", i, i, hashes[i])
		}
	*/
	fmt.Printf("benchmark32s: dup check n=%d\n", n)
	//dups, mrun := checkForDups32(hashes)
	//fmt.Printf("benchmark32: dups=%d, mrun=%d\n", dups, mrun)
}
113613
func runtimeArchitecture() (string, error) {
	cmd := exec.Command("/usr/bin/uname", "-m")
	machine, err := cmd.Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(machine)), nil
}
633172
func RunPreparation() {
	Time = NewClock()

	if !opts.HeadlessMode {
		window.Call("addEventListener", "onbeforeunload", js.NewEventCallback(js.PreventDefault, func(event js.Value) {
			window.Call("alert", "You're closing")
		}))
	}
}
466200
func main() {
	env, err := plugins.NewEnvironment()
	env.RespondAndExitIfError(err)

	var stats *statistics.DocumentStatistics

	for _, model := range env.Request.Models {
		switch model.TypeUrl {
		case "openapi.v2.Document":
			documentv2 := &openapiv2.Document{}
			err = proto.Unmarshal(model.Value, documentv2)
			if err == nil {
				// Analyze the API document.
				stats = statistics.NewDocumentStatistics(env.Request.SourceName, documentv2)
			}
		case "openapi.v3.Document":
			documentv3 := &openapiv3.Document{}
			err = proto.Unmarshal(model.Value, documentv3)
			if err == nil {
				// Analyze the API document.
				stats = statistics.NewDocumentStatisticsV3(env.Request.SourceName, documentv3)
			}
		}
	}

	if stats != nil {
		// Return the analysis results with an appropriate filename.
		// Results are in files named "summary.json" in the same relative
		// locations as the description source files.
		file := &plugins.File{}
		file.Name = strings.Replace(stats.Name, path.Base(stats.Name), "summary.json", -1)
		file.Data, err = json.MarshalIndent(stats, "", "  ")
		file.Data = append(file.Data, []byte("\n")...)
		env.RespondAndExitIfError(err)
		env.Response.Files = append(env.Response.Files, file)
	}

	env.RespondAndExit()
}
181907
func onBenchmark(cf *CLIConf) {
	tc, err := makeClient(cf, false)
	if err != nil {
		utils.FatalError(err)
	}
	result, err := tc.Benchmark(cf.Context, client.Benchmark{
		Command:  cf.RemoteCommand,
		Threads:  cf.BenchThreads,
		Duration: cf.BenchDuration,
		Rate:     cf.BenchRate,
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, utils.UserMessageFromError(err))
		os.Exit(255)
	}
	fmt.Printf("\n")
	fmt.Printf("* Requests originated: %v\n", result.RequestsOriginated)
	fmt.Printf("* Requests failed: %v\n", result.RequestsFailed)
	if result.LastError != nil {
		fmt.Printf("* Last error: %v\n", result.LastError)
	}
	fmt.Printf("\nHistogram\n\n")
	t := asciitable.MakeTable([]string{"Percentile", "Duration"})
	for _, quantile := range []float64{25, 50, 75, 90, 95, 99, 100} {
		t.AddRow([]string{fmt.Sprintf("%v", quantile),
			fmt.Sprintf("%v ms", result.Histogram.ValueAtQuantile(quantile)),
		})
	}
	io.Copy(os.Stdout, t.AsBuffer())
	fmt.Printf("\n")
}
785770
func (b *Bench) Run(ctx context.Context) error {
	err := b.createConns(ctx)
	if err != nil {
		return err
	}

	b.createThreads(ctx)
	b.runTest(ctx)
	return nil
}
703999
func benchmark32(n int) {
	//var hashes = make(Uint32Slice, n)
	//var u = make([]uint32, 1, 1)
	bs := make([]byte, 4, 4)
	var pn = hrff.Int64{int64(n), ""}
	var ps = hrff.Int64{int64(n * 4), "B"}
	fmt.Printf("benchmark32: gen n=%d, n=%h, size=%h\n", n, pn, ps)
	start := time.Now()
	for i := 0; i < n; i++ {
		bs[0], bs[1], bs[2], bs[3] = byte(i)&0xFF, (byte(i)>>8)&0xFF, (byte(i)>>16)&0xFF, (byte(i)>>24)&0xFF
		_ = jenkins.Hash232(bs, 0)
		//hashes[i] = h
		//fmt.Printf("i=%d, 0x%08x, h=0x%08x\n", i, i, h)
	}
	stop := time.Now()
	d := tdiff(start, stop)
	hsec := hrff.Float64{(float64(n) / d.Seconds()), "hashes/sec"}
	bsec := hrff.Float64{(float64(n) * 4 / d.Seconds()), "B/sec"}
	fmt.Printf("benchmark32: %h\n", hsec)
	fmt.Printf("benchmark32: %h\n", bsec)
	return

	fmt.Printf("benchmark32: sort n=%d\n", n)
	//hashes.Sort()
	/*
		for i := 0; i < n; i++ {
			fmt.Printf("i=%d, 0x%08x, h=0x%08x\n", i, i, hashes[i])
		}
	*/
	fmt.Printf("benchmark32: dup check n=%d\n", n)
	//dups, mrun := checkForDups32(hashes)
	//fmt.Printf("benchmark32: dups=%d, mrun=%d\n", dups, mrun)
}
834936
func RunFunc(benchmarkFunc func() int, duration time.Duration, c int) *Result {
	workers := make([]Worker, c)
	for i := 0; i < c; i++ {
		workers[i] = &funcWorker{ID: i, benchmarkFunc: benchmarkFunc}
	}
	return Run(workers, duration)
}
1191097
func Benchmark(benchSize int, benchCleanup bool) {
	ids := make([]int, 0, benchSize)
	// Prepare a collection with two indexes
	tmp := "/tmp/tiedot_bench"
	os.RemoveAll(tmp)
	if benchCleanup {
		defer os.RemoveAll(tmp)
	}
	benchDB, col := mkTmpDBAndCol(tmp, "tmp")
	defer benchDB.Close()
	col.Index([]string{"nested", "nested", "str"})
	col.Index([]string{"nested", "nested", "int"})
	col.Index([]string{"nested", "nested", "float"})
	col.Index([]string{"strs"})
	col.Index([]string{"ints"})
	col.Index([]string{"floats"})

	// Benchmark document insert
	average("insert", func() {
		if _, err := col.Insert(sampleDoc(benchSize)); err != nil {
			fmt.Println("Insert error", err)
		}
	}, benchSize)

	// Collect all document IDs and benchmark document read
	col.ForEachDoc(func(id int, _ []byte) bool {
		ids = append(ids, id)
		return true
	})
	average("read", func() {
		doc, err := col.Read(ids[rand.Intn(benchSize)])
		if doc == nil || err != nil {
			fmt.Println("Read error", doc, err)
		}
	}, benchSize)

	// Benchmark lookup query (two attributes)
	average("lookup", func() {
		result := make(map[int]struct{})
		if err := db.EvalQuery(sampleQuery(benchSize), col, &result); err != nil {
			fmt.Println("Query error", err)
		}
	}, benchSize)

	// Benchmark document update
	average("update", func() {
		if err := col.Update(ids[rand.Intn(benchSize)], sampleDoc(benchSize)); err != nil {
			fmt.Println("Update error", err)
		}
	}, benchSize)

	// Benchmark document delete
	var delCount int64
	average("delete", func() {
		if err := col.Delete(ids[rand.Intn(benchSize)]); err == nil {
			atomic.AddInt64(&delCount, 1)
		}
	}, benchSize)
	fmt.Printf("Deleted %d documents\n", delCount)
}
148198
func NewBench(threads, count int, cp ConnParams, query string) *Bench {
	bench := Bench{
		Threads:    threads,
		Count:      count,
		ConnParams: cp,
		Query:      query,
		Rows:       stats.NewCounter("", ""),
		Timings:    stats.NewTimings("", "", ""),
	}
	return &bench
}
50500
func RunBenchmarkBatteryConcurrently(entries []*BenchEntry) []*BenchResult {
	var (
		mu  sync.Mutex
		wg  sync.WaitGroup
		res []*BenchResult
	)
	for _, entry := range entries {
		wg.Add(1)
		go func(entry *BenchEntry) {
			m, d, err := RepetitionDurationStats(entry.Reps, entry.Setup, entry.F, entry.TearDown)
			mu.Lock()
			defer mu.Unlock()
			defer wg.Done()
			res = append(res, &BenchResult{
				BatteryID: entry.BatteryID,
				ID:        entry.ID,
				Triples:   entry.Triples,
				Err:       err,
				Mean:      m,
				StdDev:    d,
			})
		}(entry)
	}
	wg.Wait()
	return res
}
680174
func (impl *repoImpl) runProcessorsTask(c context.Context, t *tasks.RunProcessors) error {
	// Fetch the instance to see what processors are still pending.
	inst := (&model.Instance{}).FromProto(c, t.Instance)
	switch err := datastore.Get(c, inst); {
	case err == datastore.ErrNoSuchEntity:
		return fmt.Errorf("instance %q is unexpectedly gone from the datastore", inst.InstanceID)
	case err != nil:
		return transient.Tag.Apply(err)
	}

	results := map[string]processing.Result{}

	// Grab processors we haven't ran yet.
	var run []processing.Processor
	for _, id := range inst.ProcessorsPending {
		if proc := impl.procsMap[id]; proc != nil {
			run = append(run, proc)
		} else {
			logging.Errorf(c, "Skipping unknown processor %q", id)
			results[id] = processing.Result{Err: fmt.Errorf("unknown processor %q", id)}
		}
	}

	// Exit early if there's nothing to run.
	if len(run) == 0 {
		return impl.updateProcessors(c, t.Instance, results)
	}

	// Open the package for reading.
	pkg, err := impl.packageReader(c, t.Instance.Instance)
	switch {
	case transient.Tag.In(err):
		return err // retry the whole thing
	case err != nil:
		// The package is fatally broken, give up.
		logging.WithError(err).Errorf(c, "The package can't be opened, failing all processors")
		for _, proc := range run {
			results[proc.ID()] = processing.Result{Err: err}
		}
		return impl.updateProcessors(c, t.Instance, results)
	}

	// Run the processors sequentially, since PackageReader is not very friendly
	// to concurrent access.
	var transientErrs errors.MultiError
	for _, proc := range run {
		logging.Infof(c, "Running processor %q", proc.ID())
		res, err := proc.Run(c, inst, pkg)
		if err != nil {
			logging.WithError(err).Errorf(c, "Processor %q failed transiently", proc.ID())
			transientErrs = append(transientErrs, err)
		} else {
			if res.Err != nil {
				logging.WithError(res.Err).Errorf(c, "Processor %q failed fatally", proc.ID())
			}
			results[proc.ID()] = res
		}
	}

	// Store what we've got, even if some processor may have failed to run.
	updErr := impl.updateProcessors(c, t.Instance, results)

	// Prefer errors from processors over 'updErr' if both happen. Processor
	// errors are more interesting.
	switch {
	case len(transientErrs) != 0:
		return transient.Tag.Apply(transientErrs)
	case updErr != nil:
		return updErr
	}
	return nil
}
628163
func (mrr *MultiRoutineRunner) Run(fn func()) {
	mrr.once.Do(mrr.init)
	mrr.q <- fn
}
236765
func (c *connectionBenchmark) run() *result {
	var err error
	if c.requestRate == 0 {
		c.elapsed, err = c.runFullThrottle()
	} else {
		c.elapsed, err = c.runRateLimited()
	}
	return &result{summary: c.summarize(), err: err}
}
943637
func BenchmarkSigning(b *testing.B, priv crypto.PrivKey) {
	message := []byte("Hello, world!")
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		priv.Sign(message)
	}
}
198213
func (rc *RediffContext) OptimizePatch(patchReader savior.SeekSource, patchWriter io.Writer) error {
	var err error

	if rc.SourcePool == nil {
		return errors.WithStack(fmt.Errorf("SourcePool cannot be nil"))
	}

	if rc.TargetPool == nil {
		return errors.WithStack(fmt.Errorf("TargetPool cannot be nil"))
	}

	if rc.DiffMappings == nil {
		return errors.WithStack(fmt.Errorf("AnalyzePatch must be called before OptimizePatch"))
	}

	rctx := wire.NewReadContext(patchReader)
	wctx := wire.NewWriteContext(patchWriter)

	err = wctx.WriteMagic(PatchMagic)
	if err != nil {
		return errors.WithStack(err)
	}

	err = rctx.ExpectMagic(PatchMagic)
	if err != nil {
		return errors.WithStack(err)
	}

	ph := &PatchHeader{}
	err = rctx.ReadMessage(ph)
	if err != nil {
		return errors.WithStack(err)
	}

	compression := rc.Compression
	if compression == nil {
		compression = defaultRediffCompressionSettings()
	}

	wph := &PatchHeader{
		Compression: compression,
	}
	err = wctx.WriteMessage(wph)
	if err != nil {
		return errors.WithStack(err)
	}

	rctx, err = DecompressWire(rctx, ph.Compression)
	if err != nil {
		return errors.WithStack(err)
	}

	wctx, err = CompressWire(wctx, wph.Compression)
	if err != nil {
		return errors.WithStack(err)
	}

	targetContainer := &tlc.Container{}
	err = rctx.ReadMessage(targetContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	err = wctx.WriteMessage(targetContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	sourceContainer := &tlc.Container{}
	err = rctx.ReadMessage(sourceContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	err = wctx.WriteMessage(sourceContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	sh := &SyncHeader{}
	bh := &BsdiffHeader{}
	rop := &SyncOp{}

	bdc := &bsdiff.DiffContext{
		SuffixSortConcurrency: rc.SuffixSortConcurrency,
		Partitions:            rc.Partitions,
		Stats:                 rc.BsdiffStats,
		MeasureMem:            rc.MeasureMem,
	}

	if rc.Timeline != nil {
		rc.Timeline.Groups = append(rc.Timeline.Groups, TimelineGroup{
			ID:      0,
			Content: "Worker",
		})
	}

	initialStart := time.Now()
	bconsumer := &state.Consumer{}

	var biggestSourceFile int64
	var totalRediffSize int64

	for sourceFileIndex, sourceFile := range sourceContainer.Files {
		if _, ok := rc.DiffMappings[int64(sourceFileIndex)]; ok {
			if sourceFile.Size > biggestSourceFile {
				biggestSourceFile = sourceFile.Size
			}

			totalRediffSize += sourceFile.Size
		}
	}

	var doneSize int64

	for sourceFileIndex, sourceFile := range sourceContainer.Files {
		sh.Reset()
		err = rctx.ReadMessage(sh)
		if err != nil {
			return errors.WithStack(err)
		}

		if sh.FileIndex != int64(sourceFileIndex) {
			return errors.WithStack(fmt.Errorf("Malformed patch, expected index %d, got %d", sourceFileIndex, sh.FileIndex))
		}

		diffMapping := rc.DiffMappings[int64(sourceFileIndex)]

		if diffMapping == nil {
			// if no mapping, just copy ops straight up
			err = wctx.WriteMessage(sh)
			if err != nil {
				return errors.WithStack(err)
			}

			for {
				rop.Reset()
				err = rctx.ReadMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}

				if rop.Type == SyncOp_HEY_YOU_DID_IT {
					break
				}

				err = wctx.WriteMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}
			}
		} else {
			// signal bsdiff start to patcher
			sh.Reset()
			sh.FileIndex = int64(sourceFileIndex)
			sh.Type = SyncHeader_BSDIFF
			err = wctx.WriteMessage(sh)
			if err != nil {
				return errors.WithStack(err)
			}

			bh.Reset()
			bh.TargetIndex = diffMapping.TargetIndex
			err = wctx.WriteMessage(bh)
			if err != nil {
				return errors.WithStack(err)
			}

			// throw away old ops
			for {
				err = rctx.ReadMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}

				if rop.Type == SyncOp_HEY_YOU_DID_IT {
					break
				}
			}

			// then bsdiff
			sourceFileReader, err := rc.SourcePool.GetReadSeeker(int64(sourceFileIndex))
			if err != nil {
				return errors.WithStack(err)
			}

			targetFileReader, err := rc.TargetPool.GetReadSeeker(diffMapping.TargetIndex)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf(">%s", sourceFile.Path))

			_, err = sourceFileReader.Seek(0, io.SeekStart)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf("<%s", sourceFile.Path))

			_, err = targetFileReader.Seek(0, io.SeekStart)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf("*%s", sourceFile.Path))

			startTime := time.Now()

			err = bdc.Do(targetFileReader, sourceFileReader, wctx.WriteMessage, bconsumer)

			endTime := time.Now()

			if rc.Timeline != nil {
				heat := int(float64(sourceFile.Size) / float64(biggestSourceFile) * 240.0)
				rc.Timeline.Items = append(rc.Timeline.Items, TimelineItem{
					Content: filepath.Base(sourceFile.Path),
					Style:   fmt.Sprintf("background-color: hsl(%d, 100%%, 50%%)", heat),
					Title:   fmt.Sprintf("%s %s", progress.FormatBytes(sourceFile.Size), sourceFile.Path),
					Start:   startTime.Sub(initialStart).Seconds(),
					End:     endTime.Sub(initialStart).Seconds(),
					Group:   0,
				})
			}

			doneSize += sourceFile.Size
		}

		// and don't forget to indicate success
		rop.Reset()
		rop.Type = SyncOp_HEY_YOU_DID_IT

		err = wctx.WriteMessage(rop)
		if err != nil {
			return errors.WithStack(err)
		}

		rc.Consumer.Progress(float64(doneSize) / float64(totalRediffSize))
	}

	err = wctx.Close()
	if err != nil {
		return errors.WithStack(err)
	}

	return nil
}
550418
func (pm *ProtocolManager) runBenchmark(benchmarks []requestBenchmark, passCount int, targetTime time.Duration) []*benchmarkSetup {
	setup := make([]*benchmarkSetup, len(benchmarks))
	for i, b := range benchmarks {
		setup[i] = &benchmarkSetup{req: b}
	}
	for i := 0; i < passCount; i++ {
		log.Info("Running benchmark", "pass", i+1, "total", passCount)
		todo := make([]*benchmarkSetup, len(benchmarks))
		copy(todo, setup)
		for len(todo) > 0 {
			// select a random element
			index := rand.Intn(len(todo))
			next := todo[index]
			todo[index] = todo[len(todo)-1]
			todo = todo[:len(todo)-1]

			if next.err == nil {
				// calculate request count
				count := 50
				if next.totalTime > 0 {
					count = int(uint64(next.totalCount) * uint64(targetTime) / uint64(next.totalTime))
				}
				if err := pm.measure(next, count); err != nil {
					next.err = err
				}
			}
		}
	}
	log.Info("Benchmark completed")

	for _, s := range setup {
		if s.err == nil {
			s.avgTime = s.totalTime / time.Duration(s.totalCount)
		}
	}
	return setup
}