/*-------------------------------------------------------------------------- 
Computes stats on benchmark results.

@private
@param {Object} bench The benchmark instance.
@param {Object} options The options object.
179525
function compute(bench, options) {
    options || (options = {});

    var async = options.async,
        elapsed = 0,
        initCount = bench.initCount,
        minSamples = bench.minSamples,
        queue = [],
        sample = bench.stats.sample;

    /**
     * Adds a number of clones to the queue.
     */
    function enqueue(count) {
      while (count--) {
        queue.push(bench.clone({
          '_original': bench,
          'events': {
            'abort': [update],
            'cycle': [update],
            'error': [update],
            'start': [update]
          }
        }));
      }
    }

    /**
     * Updates the clone/original benchmarks to keep their data in sync.
     */
    function update(event) {
      var clone = this,
          type = event.type;

      if (bench.running) {
        if (type == 'start') {
          // Note: `clone.minTime` prop is inited in `clock()`
          clone.count = bench.initCount;
        }
        else {
          if (type == 'error') {
            bench.error = clone.error;
          }
          if (type == 'abort') {
            bench.abort();
            bench.emit('cycle');
          } else {
            event.currentTarget = event.target = bench;
            bench.emit(event);
          }
        }
      } else if (bench.aborted) {
        // clear abort listeners to avoid triggering bench's abort/cycle again
        clone.events.abort.length = 0;
        clone.abort();
      }
    }

    /**
     * Determines if more clones should be queued or if cycling should stop.
     */
    function evaluate(event) {
      var critical,
          df,
          mean,
          moe,
          rme,
          sd,
          sem,
          variance,
          clone = event.target,
          done = bench.aborted,
          now = +new Date,
          size = sample.push(clone.times.period),
          maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime,
          times = bench.times,
          varOf = function(sum, x) { return sum + pow(x - mean, 2); };

      // exit early for aborted or unclockable tests
      if (done || clone.hz == Infinity) {
        maxedOut = !(size = sample.length = queue.length = 0);
      }

      if (!done) {
        // sample mean (estimate of the population mean)
        mean = getMean(sample);
        // sample variance (estimate of the population variance)
        variance = reduce(sample, varOf, 0) / (size - 1) || 0;
        // sample standard deviation (estimate of the population standard deviation)
        sd = sqrt(variance);
        // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
        sem = sd / sqrt(size);
        // degrees of freedom
        df = size - 1;
        // critical value
        critical = tTable[Math.round(df) || 1] || tTable.infinity;
        // margin of error
        moe = sem * critical;
        // relative margin of error
        rme = (moe / mean) * 100 || 0;

        extend(bench.stats, {
          'deviation': sd,
          'mean': mean,
          'moe': moe,
          'rme': rme,
          'sem': sem,
          'variance': variance
        });

        // Abort the cycle loop when the minimum sample size has been collected
        // and the elapsed time exceeds the maximum time allowed per benchmark.
        // We don't count cycle delays toward the max time because delays may be
        // increased by browsers that clamp timeouts for inactive tabs.
        // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs
        if (maxedOut) {
          // reset the `initCount` in case the benchmark is rerun
          bench.initCount = initCount;
          bench.running = false;
          done = true;
          times.elapsed = (now - times.timeStamp) / 1e3;
        }
        if (bench.hz != Infinity) {
          bench.hz = 1 / mean;
          times.cycle = mean * bench.count;
          times.period = mean;
        }
      }
      // if time permits, increase sample size to reduce the margin of error
      if (queue.length < 2 && !maxedOut) {
        enqueue(1);
      }
      // abort the invoke cycle when done
      event.aborted = done;
    }

    // init queue and begin
    enqueue(minSamples);
    invoke(queue, {
      'name': 'run',
      'args': { 'async': async },
      'queued': true,
      'onCycle': evaluate,
      'onComplete': function() { bench.emit('complete'); }
    });
  }
1128578
function createBenchmark( len ) {
	var x;
	var i;

	x = new Array( len );
	for ( i = 0; i < len; i++ ) {
		x[ i ] = null; // TODO: set values
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var i;

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			// TODO: synchronous task
			if ( TODO/* TODO: condition */ ) {
				b.fail( 'something went wrong' );
			}
		}
		b.toc();
		if ( TODO/* TODO: condition */ ) {
			b.fail( 'something went wrong' );
		}
		b.pass( 'benchmark finished' );
		b.end();
	}
}
1289774
function Suite(type, opts) {
  Benchmark.Suite.call(this);

  opts = opts || {};
  this._type = type;
  this._compatibleType = avro.parse(type.getSchema(), {
    typeHook: typeHook,
    wrapUnions: opts.wrapUnions
  });
  this._value = opts.value ? type.fromString(opts.value) : type.random();

  Object.keys(opts).forEach(function (name) {
    if (!name.indexOf('_')) {
      return;
    }
    var fn = this['__' + name];
    if (typeof fn == 'function') {
      this.add(name, fn.call(this, opts[name])); // Add benchmark.
    }
  }, this);
}
430890
function runMicroBenchmarks(lists, resources) {
  console.log('Run micro bench...');
  // Create adb engine to use in benchmark
  const { engine, serialized } = createEngine(lists, resources, {
    loadCosmeticFilters: true,
    loadNetworkFilters: true,
  }, true /* Also serialize engine */);

  const filters = getFiltersFromLists(lists);
  const combinedLists = filters.join('\n');
  const { networkFilters, cosmeticFilters } = parseFilters(combinedLists);
  const results = {};

  // Arguments shared among benchmarks
  const args = {
    lists,
    resources,
    engine,
    filters,
    serialized,
    networkFilters,
    cosmeticFilters,
    combinedLists,
  };

  [
    benchCosmeticsFiltersParsing,
    benchEngineCreation,
    benchEngineDeserialization,
    benchEngineSerialization,
    benchGetCosmeticTokens,
    benchGetNetworkTokens,
    benchNetworkFiltersParsing,
    benchStringHashing,
    benchStringTokenize,
    benchGetCosmeticsFilters,
  ].forEach((bench) => {
    if (bench.name.toLowerCase().includes(GREP)) {
      const suite = new Benchmark.Suite();
      suite.add(bench.name, () => bench(args)).on('cycle', (event) => {
        results[bench.name] = {
          opsPerSecond: event.target.hz,
          relativeMarginOfError: event.target.stats.rme,
          numberOfSamples: event.target.stats.sample.length,
        };
      }).run({ async: false });
    }
  });

  return {
    engineStats: {
      numFilters: engine.size,
      numCosmeticFilters: engine.cosmetics.size,
      numExceptionFilters: engine.exceptions.size,
      numImportantFilters: engine.importants.size,
      numRedirectFilters: engine.redirects.size,
    },
    microBenchmarks: results,
  };
}
1340021
private void initSelects(Benchmark... benchs) {
    String opt = "<input type='checkbox' name='n' value='%ID%' %SEL%>%ID%</input><br/>";
    selectPanel.add(new HTML("<div id=selectcontainer><strong>Make your selection</strong><hr/></div>"));
    selectPanel.show();
    GQuery g = $("#selectcontainer");
    for (Benchmark b : benchs) {
      String select = opt;
      for (String s : defaultBenchmarks) {
        if (s.equals(b.getId())) {
          select = select.replaceAll("%SEL%", "checked='checked'");
        }
      }
      g.append(select.replaceAll("%ID%", b.getId() + " " + b.getName()).replaceAll("%SEL", ""));
    }
    g.append("<br/><button id=run>Run</button>");
    $("#run").click(runBenchMarks);
    selectPanel.hide();
  }
452680
private void initTrack(Benchmark... benchs) {
    if (!useTrack) return;
    String tpl = "<div id=%ID%horse class=horse><nobr><img class=himg src=images/bench/horse.gif><span>%ID%</span></nobr></div>";
    GQuery g = $("#racefield").html("");
    for (Benchmark b : benchs) {
      String id = b.getId();
      String lg = id.contains("gwt") ? "gwt" : id;
      String s = tpl.replaceAll("%ID%", id).replaceAll("%LG%", lg);
      g.append($(s));
    }

    GQuery flag = $("<img class=flag src='images/bench/animated-flag.gif'/>").appendTo(document);

    // These values are set in the css.
    int horseHeight = 35;
    int horseWidth = 150;
    int flagWidth = 35;

    int height = horseHeight * (benchs.length + 1);
    $("#racetrack").css("height", height + "px");

    trackWidth = g.width() - horseWidth - flagWidth;
    flag.hide();
  }
390366
function(opts) {
            var table = {};
            var data  = this.getTimes(opts) || {};
            Object.keys(data).sort().forEach(function(k) {
                table[k] = {
                    ms: data[k],
                    s: +((data[k] / 1000).toFixed(2))
                };
            });
            console.table(table);
        }
911326
public void runBenchmark() throws Exception {
        System.out.print(HORIZONTAL_RULE);
        System.out.println(" Setup & Initialization");
        System.out.println(HORIZONTAL_RULE);

        // connect to one or more servers, loop until success
        connect(m_client, m_config.servers);

        System.out.print("\n\n" + HORIZONTAL_RULE);
        System.out.println(" Starting Benchmark");
        System.out.println(HORIZONTAL_RULE);

        System.out.println("\nStarting bid generator\n");
        BidGenerator bidGenerator = new BidGenerator(m_client);
        long usDelay = (long) ((1.0 / BID_FREQUENCY_PER_SECOND) * 1000000.0);
        m_scheduler.scheduleWithFixedDelay(bidGenerator, 0, usDelay, TimeUnit.MICROSECONDS);

        System.out.println("\nStarting nibble deleter to delete expired data\n");
        NibbleDeleter deleter = new NibbleDeleter(m_client, m_config.displayinterval + 1);
        // Run once a second
        m_scheduler.scheduleWithFixedDelay(deleter, 1, 1, TimeUnit.SECONDS);

        System.out.println("\nWarming up...");
        final long warmupEndTime = System.currentTimeMillis() + (1000l * m_config.warmup);
        while (warmupEndTime > System.currentTimeMillis()) {
            requestAd();
        }

        // reset the stats
        m_fullStatsContext.fetchAndResetBaseline();
        m_periodicStatsContext.fetchAndResetBaseline();

        // print periodic statistics to the console
        m_benchmarkStartTS = System.currentTimeMillis();
        schedulePeriodicStats();

        // Run the benchmark loop for the requested duration
        // The throughput may be throttled depending on client configuration
        System.out.println("\nRunning benchmark...");
        final long benchmarkEndTime = System.currentTimeMillis() + (1000l * m_config.duration);
        while (benchmarkEndTime > System.currentTimeMillis()) {
            requestAd();
        }

        printResults();
        shutdown();
    }
953438
public static Benchmark setUpBenchmark(final String[] classes, final Benchmark benchmark) throws ClassNotFoundException {
        for (final String each : classes) {
            benchmark.add(Class.forName(each));
        }
        return benchmark;
    }
457147
public static void runWith(
      String[] args, Function<BenchmarkSettings, SmCodecBenchmarkState> benchmarkStateFactory) {

    BenchmarkSettings settings =
        BenchmarkSettings.from(args).durationUnit(TimeUnit.NANOSECONDS).build();

    SmCodecBenchmarkState benchmarkState = benchmarkStateFactory.apply(settings);

    benchmarkState.runForSync(
        state -> {
          BenchmarkTimer timer = state.timer("timer");
          BenchmarkMeter meter = state.meter("meter");
          ServiceMessageCodec messageCodec = state.messageCodec();
          Class<?> dataType = state.dataType();

          return i -> {
            Context timeContext = timer.time();
            ByteBuf dataBuffer = state.dataBuffer().retain();
            ByteBuf headersBuffer = state.headersBuffer().retain();
            ServiceMessage message =
                ServiceMessageCodec.decodeData(
                    messageCodec.decode(dataBuffer, headersBuffer), dataType);
            timeContext.stop();
            meter.mark();
            return message;
          };
        });
  }
369307
public function printBenchmarkIntro(Benchmark $benchmark)
    {
        printf("## %s\n", $benchmark->getName());
        if ($description = $benchmark->getDescription()) {
            printf("%s\n", $description);
        }
        print("\n");
        printf(
            "This benchmark consists of %s tests. Each test is executed %s times, the results pruned, and then averaged. %s\n\n\n",
            number_format(count($benchmark->getTests())),
            number_format($benchmark->getIterations()),
            $benchmark->getResultPruner()->getDescription()
        );
    }
190085
public static void main(String[] args) {
		StopwatchSample[] results = BenchmarkUtils.run(2, 5,
			new BenchmarkUtils.Task("enabled") {
				@Override
				public void perform() throws Exception {
					SimonManager.clear();
					SimonManager.enable();
					Stopwatch tested = SimonManager.getStopwatch("org.javasimon.stopwatch");
					for (int i = 0; i < LOOP; i++) {
						tested.start().stop();
					}
				}
			},
			new BenchmarkUtils.Task("disabled") {
				@Override
				public void perform() throws Exception {
					SimonManager.clear();
					SimonManager.enable();
					Stopwatch tested = SimonManager.getStopwatch("org.javasimon.stopwatch");
					tested.setState(SimonState.DISABLED, false);
					for (int i = 0; i < LOOP; i++) {
						tested.start().stop();
					}
				}
			},
			new BenchmarkUtils.Task("mgr-enabled") {
				@Override
				public void perform() throws Exception {
					SimonManager.clear();
					SimonManager.enable();
					for (int i = 0; i < LOOP; i++) {
						SimonManager.getStopwatch("org.javasimon.stopwatch").start().stop();
					}
				}
			},
			new BenchmarkUtils.Task("mgr-disabled") {
				@Override
				public void perform() throws Exception {
					SimonManager.clear();
					SimonManager.disable();
					for (int i = 0; i < LOOP; i++) {
						SimonManager.getStopwatch("org.javasimon.stopwatch").start().stop();
					}
				}
			},
			new BenchmarkUtils.Task("assign-ns") {
				@Override
				public void perform() throws Exception {
					for (int i = 0; i < LOOP; i++) {
						long ns = System.nanoTime();
					}
				}
			}
		);

		System.out.println("\nGoogle Chart avg:\n" +
			GoogleChartImageGenerator.barChart("10M-loop duration", results));
	}
1085253
def bench(client, n):
    
    items = list(range(n))

    # Time client publish operations
    # ------------------------------
    started = time.time()
    msg = b'x'
    for i in items:
        client.socket.send(msg)
        res = client.socket.recv()
        assert msg == res
    duration = time.time() - started

    print('Raw REQ client stats:')
    util.print_stats(n, duration)
53751
@Benchmark
    @OperationsPerInvocation(20)
    public void benchmarkJavassist(Blackhole blackHole) {
        blackHole.consume(javassistInstance.method(booleanValue));
        blackHole.consume(javassistInstance.method(byteValue));
        blackHole.consume(javassistInstance.method(shortValue));
        blackHole.consume(javassistInstance.method(intValue));
        blackHole.consume(javassistInstance.method(charValue));
        blackHole.consume(javassistInstance.method(intValue));
        blackHole.consume(javassistInstance.method(longValue));
        blackHole.consume(javassistInstance.method(floatValue));
        blackHole.consume(javassistInstance.method(doubleValue));
        blackHole.consume(javassistInstance.method(stringValue));
        blackHole.consume(javassistInstance.method(booleanValue, booleanValue, booleanValue));
        blackHole.consume(javassistInstance.method(byteValue, byteValue, byteValue));
        blackHole.consume(javassistInstance.method(shortValue, shortValue, shortValue));
        blackHole.consume(javassistInstance.method(intValue, intValue, intValue));
        blackHole.consume(javassistInstance.method(charValue, charValue, charValue));
        blackHole.consume(javassistInstance.method(intValue, intValue, intValue));
        blackHole.consume(javassistInstance.method(longValue, longValue, longValue));
        blackHole.consume(javassistInstance.method(floatValue, floatValue, floatValue));
        blackHole.consume(javassistInstance.method(doubleValue, doubleValue, doubleValue));
        blackHole.consume(javassistInstance.method(stringValue, stringValue, stringValue));
    }
21034
public void run() {
        // Reset the stats managed by the client.
        periodicStatsContext.fetchAndResetBaseline();

        // Run in a loop for config.duration seconds.
        final long benchmarkEndTime = app.startTS + (1000l * app.config.duration);
        while (benchmarkEndTime > System.currentTimeMillis()) {

            // GENERATE A RANDOM ROW

            // unique identifier and partition key
            String uuid = UUID.randomUUID().toString();

            // millisecond timestamp
            Date now = new Date();

            // for some odd reason, this will give LONG_MAX if the
            // computed value is > LONG_MAX.
            long val = (long) (rand.nextGaussian() * 1000.0);

            // CALL THE USER'S SELECTED FLAVOR OF INSERT

            try {
                // Do an vanilla insert.
                if (!app.config.inline) {
                    basicInsert(uuid, val, now);
                }
                // Do an insert with date-based deleting
                else if (app.config.historyseconds > 0) {
                    insertWithDateDelete(uuid, val, now);
                }
                // Do an insert with timestamp-based deleting
                else if (app.config.maxrows > 0) {
                    insertWithRowcountDelete(uuid, val, now);
                }
            }
            catch (IOException e) {
                // Not being super picky about failure handling. If this
                // fails, it will show up in the client-side statistics we
                // print out in printReport().
            }
        }

        // When ready to end processing...
        try {
            // Block until all async calls have returned.
            client.drain();
            // Clean close of the client connection.
            client.close();
        }
        catch (IOException | InterruptedException e) {
            // Live dangerously and ignore this error that probably
            // won't happen at shutdown time.
        }

    }
866580
def benchmark_setup(self):
        
        def f():
            self._setup()
            self.mod_ext.synchronize(**self.ext_kwargs)
        f()  # Ignore first
        self.setup_stat = self._calc_benchmark_stat(f)
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)
}