// AddGraphTriplesBenchmark creates the benchmark.
519776
func AddGraphTriplesBenchmark(ctx context.Context, st storage.Store, chanSize, bulkSize int) ([]*runtime.BenchEntry, error) {
	nodes := []int{317, 1000}
	sizes := []int{10, 1000, 100000}
	var trplSets [][]*triple.Triple
	var ids []string
	var gids []string
	var gSizes []int
	gs, err := getGraphGenerators(nodes)
	if err != nil {
		return nil, err
	}
	for idx, g := range gs {
		for _, s := range sizes {
			ts, err := g.Generate(s)
			if err != nil {
				return nil, err
			}
			trplSets = append(trplSets, ts)
			ids = append(ids, fmt.Sprintf("rg nodes=%04d, size=%07d", nodes[idx], s))
			gids = append(gids, fmt.Sprintf("n%d_s%d", nodes[idx], s))
			gSizes = append(gSizes, s)
		}
	}
	var bes []*runtime.BenchEntry
	reps := []int{10}
	for i, max := 0, len(ids); i < max; i++ {
		for idxReps, r := range reps {
			var g storage.Graph
			gID := fmt.Sprintf("add_graph_%s_r%d_i%d", gids[i], i, idxReps)
			data := trplSets[i]
			bes = append(bes, &runtime.BenchEntry{
				BatteryID: "Add non existing triples",
				ID:        fmt.Sprintf("%s, reps=%02d", ids[i], r),
				Triples:   gSizes[i],
				Reps:      r,
				Setup: func() error {
					var err error
					g, err = st.NewGraph(ctx, gID)
					return err
				},
				F: func() error {
					return g.AddTriples(ctx, data)
				},
				TearDown: func() error {
					return st.DeleteGraph(ctx, gID)
				},
			})
		}
	}
	return bes, nil
}
779936
func AddOutputEdges(g osgraph.MutableUniqueGraph, node *buildgraph.BuildConfigNode) {
	if node.BuildConfig.Spec.Output.To == nil {
		return
	}
	out := imageRefNode(g, node.BuildConfig.Spec.Output.To, node.BuildConfig)
	g.AddEdge(node, out, BuildOutputEdgeKind)
}
13706
func (s *ShapeIndex) addFaceEdge(fe faceEdge, allEdges [][]faceEdge) {
	aFace := face(fe.edge.V0.Vector)
	// See if both endpoints are on the same face, and are far enough from
	// the edge of the face that they don't intersect any (padded) adjacent face.
	if aFace == face(fe.edge.V1.Vector) {
		x, y := validFaceXYZToUV(aFace, fe.edge.V0.Vector)
		fe.a = r2.Point{x, y}
		x, y = validFaceXYZToUV(aFace, fe.edge.V1.Vector)
		fe.b = r2.Point{x, y}

		maxUV := 1 - cellPadding
		if math.Abs(fe.a.X) <= maxUV && math.Abs(fe.a.Y) <= maxUV &&
			math.Abs(fe.b.X) <= maxUV && math.Abs(fe.b.Y) <= maxUV {
			allEdges[aFace] = append(allEdges[aFace], fe)
			return
		}
	}

	// Otherwise, we simply clip the edge to all six faces.
	for face := 0; face < 6; face++ {
		if aClip, bClip, intersects := ClipToPaddedFace(fe.edge.V0, fe.edge.V1, face, cellPadding); intersects {
			fe.a = aClip
			fe.b = bClip
			allEdges[face] = append(allEdges[face], fe)
		}
	}
	return
}
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
}
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")
}
837057
func (s *Statement) AddWorkingGraphClause() {
	if s.workingClause != nil && !s.workingClause.IsEmpty() {
		s.pattern = append(s.pattern, s.workingClause)
	}
	s.ResetWorkingGraphClause()
}
879772
func (s *ShapeIndex) addShapeInternal(shapeID int32, allEdges [][]faceEdge, t *tracker) {
	shape, ok := s.shapes[shapeID]
	if !ok {
		// This shape has already been removed.
		return
	}

	faceEdge := faceEdge{
		shapeID:     shapeID,
		hasInterior: shape.Dimension() == 2,
	}

	if faceEdge.hasInterior {
		t.addShape(shapeID, containsBruteForce(shape, t.focus()))
	}

	numEdges := shape.NumEdges()
	for e := 0; e < numEdges; e++ {
		edge := shape.Edge(e)

		faceEdge.edgeID = e
		faceEdge.edge = edge
		faceEdge.maxLevel = maxLevelForEdge(edge)
		s.addFaceEdge(faceEdge, allEdges)
	}
}
129552
func (tc *TeleportClient) Benchmark(ctx context.Context, bench Benchmark) (*BenchmarkResult, error) {
	tc.Stdout = ioutil.Discard
	tc.Stderr = ioutil.Discard
	tc.Stdin = &bytes.Buffer{}

	ctx, cancel := context.WithTimeout(ctx, bench.Duration)
	defer cancel()

	requestC := make(chan *benchMeasure)
	responseC := make(chan *benchMeasure, bench.Threads)

	// create goroutines for concurrency
	for i := 0; i < bench.Threads; i++ {
		thread := &benchmarkThread{
			id:          i,
			ctx:         ctx,
			client:      tc,
			command:     bench.Command,
			interactive: bench.Interactive,
			receiveC:    requestC,
			sendC:       responseC,
		}
		go thread.run()
	}

	// producer goroutine
	go func() {
		interval := time.Duration(float64(1) / float64(bench.Rate) * float64(time.Second))
		ticker := time.NewTicker(interval)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				// notice how we start the timer regardless of whether any goroutine can process it
				// this is to account for coordinated omission,
				// http://psy-lob-saw.blogspot.com/2015/03/fixing-ycsb-coordinated-omission.html
				measure := &benchMeasure{
					Start: time.Now(),
				}
				select {
				case requestC <- measure:
				case <-ctx.Done():
					return
				}
			case <-ctx.Done():
				return
			}
		}
	}()

	var result BenchmarkResult
	// from one millisecond to 60000 milliseconds (minute) with 3 digits precision
	result.Histogram = hdrhistogram.New(1, 60000, 3)

	var doneThreads int
	var timeoutC <-chan time.Time
	doneC := ctx.Done()
	for {
		select {
		case <-timeoutC:
			result.LastError = trace.BadParameter("several requests hang: timeout waiting for %v threads to finish", bench.Threads-doneThreads)
			return &result, nil
		case <-doneC:
			// give it a couple of seconds to wrap up the goroutines,
			// set up the timer that will fire up if the all goroutines were not finished
			doneC = nil
			waitTime := time.Duration(result.Histogram.Max()) * time.Millisecond
			// going to wait latency + buffer to give requests in flight to wrap up
			waitTime = time.Duration(1.2 * float64(waitTime))
			timeoutC = time.After(waitTime)
		case measure := <-responseC:
			if measure.ThreadCompleted {
				doneThreads += 1
				if doneThreads == bench.Threads {
					return &result, nil
				}
			} else {
				if measure.Error != nil {
					result.RequestsFailed += 1
					result.LastError = measure.Error
				}
				result.RequestsOriginated += 1
				result.Histogram.RecordValue(int64(measure.End.Sub(measure.Start) / time.Millisecond))
			}
		}
	}

}
897114
func (d *ChainDescriber) MakeGraph() (osgraph.Graph, error) {
	g := osgraph.New()

	loaders := []GraphLoader{}
	for namespace := range d.namespaces {
		klog.V(4).Infof("Loading build configurations from %q", namespace)
		loaders = append(loaders, &bcLoader{namespace: namespace, lister: d.c})
	}
	loadingFuncs := []func() error{}
	for _, loader := range loaders {
		loadingFuncs = append(loadingFuncs, loader.Load)
	}

	if errs := parallel.Run(loadingFuncs...); len(errs) > 0 {
		return g, utilerrors.NewAggregate(errs)
	}

	for _, loader := range loaders {
		loader.AddToGraph(g)
	}

	buildedges.AddAllInputOutputEdges(g)

	return g, nil
}
482155
func NewGraph() *Graph {
	return &Graph{
		edges: make(map[uint32](map[uint32]float64)),
		nodes: make(map[uint32]*node),
	}
}
538620
func (g *SimpleGraph) AddEdge(v, w interface{}) error {
	g.mutex.Lock()
	defer g.mutex.Unlock()

	if v == w {
		return ErrSelfLoop
	}

	g.addVertex(v)
	g.addVertex(w)

	if _, ok := g.adjacencyList[v][w]; ok {
		return ErrParallelEdge
	}

	g.adjacencyList[v][w] = struct{}{}
	g.adjacencyList[w][v] = struct{}{}
	g.e++
	return nil
}
394220
func (h *HTTPSink) AddSpans(ctx context.Context, traces []*trace.Span) (err error) {
	if len(traces) == 0 || h.TraceEndpoint == "" {
		return nil
	}
	return h.doBottom(ctx, func() (io.Reader, bool, error) {
		b, err := h.jsonMarshal(traces)
		if err != nil {
			return nil, false, errors.Annotate(err, "cannot encode traces into json")
		}
		return h.getReader(b)
	}, "application/json", h.TraceEndpoint, spanResponseValidator)
}
1096994
func (g *marshalGraph) add(v *marshalVertex) {
	g.Vertices = append(g.Vertices, v)
	sort.Sort(vertices(g.Vertices))
}
1204094
func (b *blame) sliceGraph(i int) []*object.Commit {
	fVs := b.graph[i]
	result := make([]*object.Commit, 0, len(fVs))
	for _, v := range fVs {
		c := object.Commit(*v)
		result = append(result, &c)
	}
	return result
}
889822
func (g *Generator) AddLinuxResourcesHugepageLimit(pageSize string, limit uint64) {
	hugepageLimit := rspec.LinuxHugepageLimit{
		Pagesize: pageSize,
		Limit:    limit,
	}

	g.initConfigLinuxResources()
	for i, pageLimit := range g.Config.Linux.Resources.HugepageLimits {
		if pageLimit.Pagesize == pageSize {
			g.Config.Linux.Resources.HugepageLimits[i].Limit = limit
			return
		}
	}
	g.Config.Linux.Resources.HugepageLimits = append(g.Config.Linux.Resources.HugepageLimits, hugepageLimit)
}
1249882
func (p *pruner) addBuildsToGraph(builds *buildv1.BuildList) []error {
	var errs []error

	for i := range builds.Items {
		build := &builds.Items[i]
		ref := getRef(build)
		klog.V(4).Infof("Examining %s", getKindName(ref))
		buildNode := buildgraph.EnsureBuildNode(p.g, build)
		errs = append(errs, p.addBuildStrategyImageReferencesToGraph(ref, build.Spec.Strategy, buildNode)...)
	}

	return errs
}
1189354
func (g *Graph) MakeEdge(from, to Node) error {
	return g.MakeEdgeWeight(from, to, 0)
}