Benchmark n requests
180239
def bench(client, n):
    
    items = list(range(n))

    # Time client publish operations
    # ------------------------------
    started = time.time()
    for i in items:
        client.publish('test', i)
    duration = time.time() - started

    print('Publisher client stats:')
    util.print_stats(n, duration)
1187521
def bench(client, n):
    
    pairs = [(x, x + 1) for x in range(n)]

    started = time.time()
    for pair in pairs:
        res, err = client.call('add', *pair)
        # assert err is None
    duration = time.time() - started
    print('Client stats:')
    util.print_stats(n, duration)
959382
def benchmark(src_dir, compiler, include_dirs, iter_count):
    """"""

    files = list(files_in_dir(src_dir, 'cpp'))
    random.shuffle(files)
    has_string_templates = True
    string_template_file_cnt = sum(1 for file in files if 'bmp' in file)
    file_count = len(files) + string_template_file_cnt

    started_at = time.time()
    result = {}
    for filename in files:
        progress = len(result)
        result[filename] = benchmark_file(
            os.path.join(src_dir, filename),
            compiler,
            include_dirs,
            (float(progress) / file_count, float(progress + 1) / file_count),
            iter_count
        )
        if 'bmp' in filename and has_string_templates:
            try:
                temp_result = benchmark_file(
                    os.path.join(src_dir, filename),
                    compiler,
                    include_dirs,
                    (float(progress + 1) / file_count, float(progress + 2) / file_count),
                    iter_count,
                    '-Xclang -fstring-literal-templates'
                )
                result[filename.replace('bmp', 'slt')] = temp_result
            except:
                has_string_templates = False
                file_count -= string_template_file_cnt
                print 'Stopping the benchmarking of string literal templates'

        elapsed = time.time() - started_at
        total = float(file_count * elapsed) / len(result)
        print 'Elapsed time: {0}, Remaining time: {1}'.format(
            format_time(elapsed),
            format_time(total - elapsed)
        )
    return result
18428
def main(fast=False):
    """"""
    print('Running benchmarks...\n')
    results = bench_run(fast=fast)
    bench_report(results)
271394
public void run() throws Exception {
    if (config == null) {
      return;
    }

    SimpleRequest req = newRequest();

    List<ManagedChannel> channels = new ArrayList<>(config.channels);
    for (int i = 0; i < config.channels; i++) {
      channels.add(config.newChannel());
    }

    // Do a warmup first. It's the same as the actual benchmark, except that
    // we ignore the statistics.
    warmup(req, channels);

    long startTime = System.nanoTime();
    long endTime = startTime + TimeUnit.SECONDS.toNanos(config.duration);
    List<Histogram> histograms = doBenchmark(req, channels, endTime);
    long elapsedTime = System.nanoTime() - startTime;

    Histogram merged = merge(histograms);

    printStats(merged, elapsedTime);
    if (config.histogramFile != null) {
      saveHistogram(merged, config.histogramFile);
    }
    shutdown(channels);
  }
522379
def main():
    """"""
    desc = 'Benchmark the files generated by generate.py'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument(
        '--src',
        dest='src_dir',
        default='generated',
        help='The directory containing the sources to benchmark'
    )
    parser.add_argument(
        '--out',
        dest='out_dir',
        default='../../doc',
        help='The output directory'
    )
    parser.add_argument(
        '--include',
        dest='include',
        default='include',
        help='The directory containing the headeres for the benchmark'
    )
    parser.add_argument(
        '--boost_headers',
        dest='boost_headers',
        default='../../../..',
        help='The directory containing the Boost headers (the boost directory)'
    )
    parser.add_argument(
        '--compiler',
        dest='compiler',
        default='g++',
        help='The compiler to do the benchmark with'
    )
    parser.add_argument(
        '--repeat_count',
        dest='repeat_count',
        type=int,
        default=5,
        help='How many times a measurement should be repeated.'
    )

    args = parser.parse_args()

    compiler = compiler_info(args.compiler)
    results = benchmark(
        args.src_dir,
        args.compiler,
        [args.include, args.boost_headers],
        args.repeat_count
    )

    plot_diagrams(results, configs_in(args.src_dir), compiler, args.out_dir)
14055
function initializePerformance(req, _resp, next) {
    req.amorphicTracking = {
        startTime: process.hrtime(),
        serverTasks: [],
        browserTasks: [],
        loggingContext: {},
        addServerTask: function addTask(props, hrStartTime) {
            let diff = process.hrtime(hrStartTime);
            let took = (diff[0] * 1e9 + diff[1]) / 1000000;
            props.time = took;
            this.serverTasks.push(props);
        }
    };

    next();
}
204321
function (benchmark, simultaneousRequests, done) {
	var pageName,
		engineName;

	this.benchmark = benchmark;
	this.simultaneousRequests = simultaneousRequests;
	this.done = done;

	if (typeof simultaneousRequests !== "number") {
		throw new Error("simultaneousRequests must be an integer; " + (typeof simultaneousRequests) + " passed");
	}
	if (simultaneousRequests < 1) {
		throw new Error("simultaneousRequests must be at least 1; " + simultaneousRequests + " passed");
	}

	this.responseTimes = {};
	for (pageName in this.benchmark.pages) {
		this.responseTimes[pageName] = {};
		for (engineName in this.benchmark.engines) {
			this.responseTimes[pageName][engineName] = [];
		}
	}

	this.totals = {};
}
523804
def _thread_worker_fn(samples, batchify_fn, dataset):
    """"""
    if isinstance(samples[0], (list, tuple)):
        batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples]
    else:
        batch = batchify_fn([dataset[i] for i in samples])
    return batch
307585
function displayPerformance(req) {
    let logger = Semotus.createLogger();

    logger.setContextProps(req.amorphicTracking.loggingContext);

    let diff = process.hrtime(req.amorphicTracking.startTime);
    let totalTime = (diff[0] * 1e9 + diff[1]) / 1000000;
    let taskTime = 0;

    req.amorphicTracking.serverTasks.forEach(function d(task) {
        taskTime += task.time;
    });

    logger.info({
        component: 'amorphic',
        module: 'listen',
        duration: totalTime,
        browserPerformance: req.amorphicTracking.browser,
        serverTasks: req.amorphicTracking.serverTasks,
        unaccounted: totalTime - taskTime},
        'Request Performance');
}
1084593
function performance() {
  /* eslint prefer-rest-params: 0 */
  const args = Array.from(arguments);
  const interval = get(args, isNumber, 100);
  const fn = get(args, isFunction, noop);
  const unitInfo = convertUnit(get(args, isString, 'B').toUpperCase());
  let start = process.hrtime();
  let cpuUsage = process.cpuUsage && process.cpuUsage();
  const timer = setInterval(() => {
    let result = {
      lag: getDelay(start, interval),
      heap: getHeapStatistics(unitInfo),
      memoryUsage: getMemoryUsage(unitInfo),
    };
    if (cpuUsage) {
      result.cpuUsage = getCpuUsage(cpuUsage, start);
    }
    if (v8.getHeapSpaceStatistics) {
      result.heapSpace = getHeapSpaceStatistics(unitInfo);
    }
    if (performance.flatten) {
      result = flatten(result);
    }
    if (performance.camelCase) {
      result = camelCaseData(result);
    }
    fn(result);
    start = process.hrtime();
    cpuUsage = process.cpuUsage && process.cpuUsage();
  }, interval);
  timer.unref();
  return timer;
}
1135413
def print_benchmark(self):
        """"""
        print('%-7.2f %s' % (self.elapsed, 'seconds elapsed'))
        if self.elapsed:
            for key in self._benchmark_keys:
                print('%-7d %s per second (%d total)' %
                      (self.counters[key] / self.elapsed, key,
                       self.counters[key]))
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,
  };
}
510388
function getCpuCurrentSpeedSync() {

  let cpus = os.cpus();
  let minFreq = 999999999;
  let maxFreq = 0;
  let avgFreq = 0;
  let cores = [];

  if (cpus.length) {
    for (let i in cpus) {
      if (cpus.hasOwnProperty(i)) {
        avgFreq = avgFreq + cpus[i].speed;
        if (cpus[i].speed > maxFreq) maxFreq = cpus[i].speed;
        if (cpus[i].speed < minFreq) minFreq = cpus[i].speed;
      }
      cores.push(parseFloat(((cpus[i].speed + 1) / 1000).toFixed(2)));
    }
    avgFreq = avgFreq / cpus.length;
    return {
      min: parseFloat(((minFreq + 1) / 1000).toFixed(2)),
      max: parseFloat(((maxFreq + 1) / 1000).toFixed(2)),
      avg: parseFloat(((avgFreq + 1) / 1000).toFixed(2)),
      cores: cores
    };
  } else {
    return {
      min: 0,
      max: 0,
      avg: 0,
      cores: cores
    };
  }
}
1328343
def benchmark(cls, sysinfo=True):
        

        #
        # PRINT PLATFORM
        #
        if sysinfo:
            data_platform = systeminfo()
            print(Printer.attribute(data_platform,
                                    ["Machine Arribute", "Time/s"]))

        #
        # PRINT TIMERS
        #
        timers = StopWatch.keys()

        data_timers = {}
        for timer in timers:
            data_timers[timer] = {
                'time': round(StopWatch.get(timer), 2),
                'timer': timer
            }
            for attribute in ["node", "system", "machine", "mac_version",
                              "win_version"]:
                data_timers[timer][attribute] = data_platform[attribute]

        # print(Printer.attribute(data_timers, header=["Command", "Time/s"]))
        print(Printer.write(
            data_timers,
            order=["timer", "time", "node", "system", "mac_version",
                   "win_version"]
        ))

        print()
        print(Printer.write(
            data_timers,
            order=["timer", "time", "node", "system", "mac_version",
                   "win_version"],
            output="csv"
        ))
1123885
def benchmark(store, n=10000):
    
    x = UpdatableItem(store=store, count=0)
    for _ in xrange(n):
        x.count += 1
344250
def benchmark(message)
      start = Time.now
      print(stdout, "#{message} ")
      result = yield
      duration = Time.now - start
      info("✔".green + format(" %0.3fs", duration).gray)
      result
    rescue
      info("✘".red)
      raise
    end