Micro benchmarks are a set of benchmarks measuring specific aspects of the library
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,
  };
}
675826
function clock() {
      var options = Benchmark.options,
          templateData = {},
          timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }];

      // Lazy define for hi-res timers.
      clock = function(clone) {
        var deferred;

        if (clone instanceof Deferred) {
          deferred = clone;
          clone = deferred.benchmark;
        }
        var bench = clone._original,
            stringable = isStringable(bench.fn),
            count = bench.count = clone.count,
            decompilable = stringable || (support.decompilation && (clone.setup !== _.noop || clone.teardown !== _.noop)),
            id = bench.id,
            name = bench.name || (typeof id == 'number' ? '<Test #' + id + '>' : id),
            result = 0;

        // Init `minTime` if needed.
        clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime);

        // Compile in setup/teardown functions and the test loop.
        // Create a new compiled test, instead of using the cached `bench.compiled`,
        // to avoid potential engine optimizations enabled over the life of the test.
        var funcBody = deferred
          ? 'var d#=this,${fnArg}=d#,m#=d#.benchmark._original,f#=m#.fn,su#=m#.setup,td#=m#.teardown;' +
            // When `deferred.cycles` is `0` then...
            'if(!d#.cycles){' +
            // set `deferred.fn`,
            'd#.fn=function(){var ${fnArg}=d#;if(typeof f#=="function"){try{${fn}\n}catch(e#){f#(d#)}}else{${fn}\n}};' +
            // set `deferred.teardown`,
            'd#.teardown=function(){d#.cycles=0;if(typeof td#=="function"){try{${teardown}\n}catch(e#){td#()}}else{${teardown}\n}};' +
            // execute the benchmark's `setup`,
            'if(typeof su#=="function"){try{${setup}\n}catch(e#){su#()}}else{${setup}\n};' +
            // start timer,
            't#.start(d#);' +
            // and then execute `deferred.fn` and return a dummy object.
            '}d#.fn();return{uid:"${uid}"}'

          : 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count,n#=t#.ns;${setup}\n${begin};' +
            'while(i#--){${fn}\n}${end};${teardown}\nreturn{elapsed:r#,uid:"${uid}"}';

        var compiled = bench.compiled = clone.compiled = createCompiled(bench, decompilable, deferred, funcBody),
            isEmpty = !(templateData.fn || stringable);

        try {
          if (isEmpty) {
            // Firefox may remove dead code from `Function#toString` results.
            // For more information see http://bugzil.la/536085.
            throw new Error('The test "' + name + '" is empty. This may be the result of dead code removal.');
          }
          else if (!deferred) {
            // Pretest to determine if compiled code exits early, usually by a
            // rogue `return` statement, by checking for a return object with the uid.
            bench.count = 1;
            compiled = decompilable && (compiled.call(bench, context, timer) || {}).uid == templateData.uid && compiled;
            bench.count = count;
          }
        } catch(e) {
          compiled = null;
          clone.error = e || new Error(String(e));
          bench.count = count;
        }
        // Fallback when a test exits early or errors during pretest.
        if (!compiled && !deferred && !isEmpty) {
          funcBody = (
            stringable || (decompilable && !clone.error)
              ? 'function f#(){${fn}\n}var r#,s#,m#=this,i#=m#.count'
              : 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count'
            ) +
            ',n#=t#.ns;${setup}\n${begin};m#.f#=f#;while(i#--){m#.f#()}${end};' +
            'delete m#.f#;${teardown}\nreturn{elapsed:r#}';

          compiled = createCompiled(bench, decompilable, deferred, funcBody);

          try {
            // Pretest one more time to check for errors.
            bench.count = 1;
            compiled.call(bench, context, timer);
            bench.count = count;
            delete clone.error;
          }
          catch(e) {
            bench.count = count;
            if (!clone.error) {
              clone.error = e || new Error(String(e));
            }
          }
        }
        // If no errors run the full test loop.
        if (!clone.error) {
          compiled = bench.compiled = clone.compiled = createCompiled(bench, decompilable, deferred, funcBody);
          result = compiled.call(deferred || bench, context, timer).elapsed;
        }
        return result;
      };

      /*----------------------------------------------------------------------*/

      /**
       * Creates a compiled function from the given function `body`.
       */
      function createCompiled(bench, decompilable, deferred, body) {
        var fn = bench.fn,
            fnArg = deferred ? getFirstArgument(fn) || 'deferred' : '';

        templateData.uid = uid + uidCounter++;

        _.assign(templateData, {
          'setup': decompilable ? getSource(bench.setup) : interpolate('m#.setup()'),
          'fn': decompilable ? getSource(fn) : interpolate('m#.fn(' + fnArg + ')'),
          'fnArg': fnArg,
          'teardown': decompilable ? getSource(bench.teardown) : interpolate('m#.teardown()')
        });

        // Use API of chosen timer.
        if (timer.unit == 'ns') {
          _.assign(templateData, {
            'begin': interpolate('s#=n#()'),
            'end': interpolate('r#=n#(s#);r#=r#[0]+(r#[1]/1e9)')
          });
        }
        else if (timer.unit == 'us') {
          if (timer.ns.stop) {
            _.assign(templateData, {
              'begin': interpolate('s#=n#.start()'),
              'end': interpolate('r#=n#.microseconds()/1e6')
            });
          } else {
            _.assign(templateData, {
              'begin': interpolate('s#=n#()'),
              'end': interpolate('r#=(n#()-s#)/1e6')
            });
          }
        }
        else if (timer.ns.now) {
          _.assign(templateData, {
            'begin': interpolate('s#=n#.now()'),
            'end': interpolate('r#=(n#.now()-s#)/1e3')
          });
        }
        else {
          _.assign(templateData, {
            'begin': interpolate('s#=new n#().getTime()'),
            'end': interpolate('r#=(new n#().getTime()-s#)/1e3')
          });
        }
        // Define `timer` methods.
        timer.start = createFunction(
          interpolate('o#'),
          interpolate('var n#=this.ns,${begin};o#.elapsed=0;o#.timeStamp=s#')
        );

        timer.stop = createFunction(
          interpolate('o#'),
          interpolate('var n#=this.ns,s#=o#.timeStamp,${end};o#.elapsed=r#')
        );

        // Create compiled test.
        return createFunction(
          interpolate('window,t#'),
          'var global = window, clearTimeout = global.clearTimeout, setTimeout = global.setTimeout;\n' +
          interpolate(body)
        );
      }

      /**
       * Gets the current timer's minimum resolution (secs).
       */
      function getRes(unit) {
        var measured,
            begin,
            count = 30,
            divisor = 1e3,
            ns = timer.ns,
            sample = [];

        // Get average smallest measurable time.
        while (count--) {
          if (unit == 'us') {
            divisor = 1e6;
            if (ns.stop) {
              ns.start();
              while (!(measured = ns.microseconds())) {}
            } else {
              begin = ns();
              while (!(measured = ns() - begin)) {}
            }
          }
          else if (unit == 'ns') {
            divisor = 1e9;
            begin = (begin = ns())[0] + (begin[1] / divisor);
            while (!(measured = ((measured = ns())[0] + (measured[1] / divisor)) - begin)) {}
            divisor = 1;
          }
          else if (ns.now) {
            begin = ns.now();
            while (!(measured = ns.now() - begin)) {}
          }
          else {
            begin = new ns().getTime();
            while (!(measured = new ns().getTime() - begin)) {}
          }
          // Check for broken timers.
          if (measured > 0) {
            sample.push(measured);
          } else {
            sample.push(Infinity);
            break;
          }
        }
        // Convert to seconds.
        return getMean(sample) / divisor;
      }

      /**
       * Interpolates a given template string.
       */
      function interpolate(string) {
        // Replaces all occurrences of `#` with a unique number and template tokens with content.
        return _.template(string.replace(/\#/g, /\d+/.exec(templateData.uid)))(templateData);
      }

      /*----------------------------------------------------------------------*/

      // Detect Chrome's microsecond timer:
      // enable benchmarking via the --enable-benchmarking command
      // line switch in at least Chrome 7 to use chrome.Interval
      try {
        if ((timer.ns = new (context.chrome || context.chromium).Interval)) {
          timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
        }
      } catch(e) {}

      // Detect Node.js's nanosecond resolution timer available in Node.js >= 0.8.
      if (processObject && typeof (timer.ns = processObject.hrtime) == 'function') {
        timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
      }
      // Detect Wade Simmons' Node.js `microtime` module.
      if (microtimeObject && typeof (timer.ns = microtimeObject.now) == 'function') {
        timers.push({ 'ns': timer.ns,  'res': getRes('us'), 'unit': 'us' });
      }
      // Pick timer with highest resolution.
      timer = _.minBy(timers, 'res');

      // Error if there are no working timers.
      if (timer.res == Infinity) {
        throw new Error('Benchmark.js was unable to find a working timer.');
      }
      // Resolve time span required to achieve a percent uncertainty of at most 1%.
      // For more information see http://spiff.rit.edu/classes/phys273/uncert/uncert.html.
      options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05));
      return clock.apply(null, arguments);
    }
891477
def run_benchmarks(dir, models, wav, alphabet, lm_binary=None, trie=None, iters=-1):
    
    '''

    assert_valid_dir(dir)

    inference_times = [ ]

    for model in models:
        model_filename = model

        current_model = {
          'name':   model,
          'iters':  [ ],
          'mean':   numpy.infty,
          'stddev': numpy.infty
        }

        if lm_binary and trie:
            cmdline = './deepspeech --model "%s" --alphabet "%s" --lm "%s" --trie "%s" --audio "%s" -t' % (model_filename, alphabet, lm_binary, trie, wav)
        else:
            cmdline = './deepspeech --model "%s" --alphabet "%s" --audio "%s" -t' % (model_filename, alphabet, wav)

        for it in range(iters):
            sys.stdout.write('\rRunning %s: %d/%d' % (os.path.basename(model), (it+1), iters))
            sys.stdout.flush()
            rc, stdout, stderr = exec_command(cmdline, cwd=dir)
            if rc == 0:
                inference_time = float(stdout.split('\n')[1].split('=')[-1])
                # print("[%d] model=%s inference=%f" % (it, model, inference_time))
                current_model['iters'].append(inference_time)
            else:
                print('exec_command("%s") failed with rc=%d' % (cmdline, rc))
                print('stdout: %s' % stdout)
                print('stderr: %s' % stderr)
                raise AssertionError('Execution failure: rc=%d' % (rc))

        sys.stdout.write('\n')
        sys.stdout.flush()
        current_model['mean']   = numpy.mean(current_model['iters'])
        current_model['stddev'] = numpy.std(current_model['iters'])
        inference_times.append(current_model)

    return inference_times
303456
def benchmark_profiles
      sds          = ::OpenSCAP::DS::Sds.new(source)
      bench_source = sds.select_checklist!
      benchmark = ::OpenSCAP::Xccdf::Benchmark.new(bench_source)
      sds.destroy
      benchmark
    end
422694
ImmutableSet<Experiment> dryRun(Iterable<Experiment> experiments)
      throws InvalidBenchmarkException {
    ImmutableSet.Builder<Experiment> builder = ImmutableSet.builder();
    for (Experiment experiment : experiments) {
      Class<?> clazz = benchmarkClass.benchmarkClass();
      try {
        Object benchmark = injector.createChildInjector(ExperimentModule.forExperiment(experiment))
            .getInstance(Key.get(clazz));
        benchmarkClass.setUpBenchmark(benchmark);
        try {
          experiment.instrumentation().dryRun(benchmark);
          builder.add(experiment);
        } finally {
          // discard 'benchmark' now; the worker will have to instantiate its own anyway
          benchmarkClass.cleanup(benchmark);
        }
      } catch (ProvisionException e) {
        Throwable cause = e.getCause();
        if (cause != null) {
          throw new UserCodeException(cause);
        }
        throw e;
      } catch (CreationException e) {
        // Guice formatting is a little ugly
        StringBuilder message = new StringBuilder(
            "Could not create an instance of the benchmark class following reasons:");
        int errorNum = 0;
        for (Message guiceMessage : e.getErrorMessages()) {
          message.append("\n  ").append(++errorNum).append(") ")
              .append(guiceMessage.getMessage());
        }
        throw new InvalidBenchmarkException(message.toString(), e);
      } catch (SkipThisScenarioException innocuous) {}
    }
    return builder.build();
  }
41861
def benchmark_data(self):
        
        return self.fetch[self.benchmark_type](
            self.benchmark_code,
            self.account.start_date,
            self.account.end_date
        )
637715
double run_benchmark() {
    // use the lesser of 40MB or 10% of Heap
    final long M = Math.min(10000000l, Runtime.getRuntime().maxMemory()/40);
    int[] vals = MemoryManager.malloc4((int)M);
    double total;
    int repeats = 20;
    Timer timer = new Timer(); //ms
    long sum = 0;
    // write repeats * M ints
    // read  repeats * M ints
    for (int l=repeats-1; l>=0; --l) {
      for (int i=0; i<M; ++i) {
        vals[i] = i + l;
      }
      sum = 0;
      for (int i=0; i<M; ++i) {
        sum += vals[i];
      }
    }
    total = (double)timer.time()/1000./repeats;
    //use the sum in a way that doesn't affect the result (don't want the compiler to optimize it away)
    double time = total + ((M*(M-1)/2) - sum); // == total
    return (double)2*M*4/time; //(read+write) * 4 bytes
  }
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);
}
704228
function bench(functions, options) {
  const funcs = assertFunctions(functions);
  const opts = assertOptions(options);
  const metrics = [];
  const totalRuns = funcs.length * opts.runs;
  let runCount = 0;

  for (let i = 0; i < funcs.length; i++) {
    const func = funcs[i];
    const totals = [0, 0];
    let max = 0;
    let min = Number.MAX_SAFE_INTEGER;

    for (let j = 0; j < opts.runs; j++) {
      const start = process.hrtime();
      func.fn.call(func.bind, func.params);
      const end = process.hrtime(start);

      totals[0] += end[0];
      totals[1] += end[1];

      const ns = (end[0] * NS_PER_SEC) + end[1];
      if (ns > max) max = ns;
      if (ns < min) min = ns;

      updateStatus(++runCount, totalRuns, opts.stream);
    }

    const whole = (totals[0] / opts.runs) * NS_PER_SEC;
    const partial = totals[1] / opts.runs;
    const avg = Math.ceil(whole + partial);

    metrics.push({
      avg,
      label: func.label,
      max,
      min,
    });
  }

  opts.report(opts.stream, metrics, opts.thresholds);
  checkThresholds(metrics, opts.thresholds);

  return metrics;
}
870980
def micro_indices(self):
        """"""
        return tuple(sorted(idx for part in self.partition for idx in part))
1316310
def all_version_library_instances
      all_repos = all_version_repos.where(:library_instance_id => nil).pluck("#{Katello::Repository.table_name}.id")
      all_repos += all_version_repos.pluck(:library_instance_id)
      Repository.where(:id => all_repos)
    end
215921
def benchmark():
    
    # Use all cores but one on multi-core CPUs.
    pool_size = multiprocessing.cpu_count() - 1
    if pool_size < 1:
        pool_size = 1

    # Start a pool of workers. Only allow 1 task per child, to force flushing
    # of solver's internal caches.
    pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=1)
    results = pool.imap_unordered(run_scenario, Benchmark.scenarii)
    pool.close()
    pool.join()

    # Update CSV database with the new results.
    benchmark = Benchmark()
    benchmark.load_csv()
    benchmark.add(results)
    benchmark.save_csv()
728485
def benchmark_method(f):
    ""
    @wraps(f)
    def inner(name, *args, **kwargs):
        return Benchmark(name, f, args, kwargs)
    return inner
361295
def bench_report(results):
    """"""

    table = Table(names=['function', 'nest', 'nside', 'size',
                         'time_healpy', 'time_self', 'ratio'],
                  dtype=['S20', bool, int, int, float, float, float], masked=True)
    for row in results:
        table.add_row(row)

    table['time_self'].format = '10.7f'

    if HEALPY_INSTALLED:
        table['ratio'] = table['time_self'] / table['time_healpy']
        table['time_healpy'].format = '10.7f'
        table['ratio'].format = '7.2f'

    table.pprint(max_lines=-1)
136221
function metrics( clbk ) {
	var m = {},
		mem,
		used,
		total;

	// Get the process id:
	m.pid = process.pid;

	// Get the number of milliseconds the process has been running:
	m.uptime = process.uptime() * 1000; // ms

	// Extract process memory usage:
	mem = process.memoryUsage();
	used = mem.heapUsed;
	total = mem.heapTotal;

	m.mem = {
		'rss': mem.rss / 1000, // KB
		'heapFree': (total-used) / 1000, // KB
		'heapTotal': total / 1000, // KB
		'heapUtilization': used / total
	};

	// Get the average amount of time requests have to wait in Node's event queue before being processed:
	m.lag = toobusy.lag(); // ms

	// Get the CPU and memory consumption:
	pidusage.stat( m.pid, onStats );

	/**
	* FUNCTION: onStats( error, stat )
	*	Callback invoked upon collecting CPU and memory data for the current process.
	*
	* @private
	* @param {Object} error
	* @param {Object} stat - process data
	*/
	function onStats( error, stat ) {
		if ( error ) {
			return clbk( error );
		}
		m.mem.memUsed = stat.memory / 1000; // KB
		m.mem.utilization = stat.memory / os.totalmem();
		m.cpu = {
			'utilization': stat.cpu / 100
		};
		clbk( null, m );
	}
}
864971
def bench(participants=participants, benchmarks=benchmarks,
          bench_time=BENCH_TIME):
    """"""

    mcs = [p.factory() for p in participants]
    means = [[] for p in participants]
    stddevs = [[] for p in participants]

    # Have each lifter do one benchmark each
    last_fn = None
    for benchmark_name, fn, args, kwargs in benchmarks:
        logger.info('')
        logger.info('%s', benchmark_name)

        for i, (participant, mc) in enumerate(zip(participants, mcs)):

            # FIXME: set before bench for get
            if 'get' in fn.__name__:
                last_fn(mc, *args, **kwargs)

            sw = Stopwatch()
            while sw.total() < bench_time:
                with sw.timing():
                    fn(mc, *args, **kwargs)

            means[i].append(sw.mean())
            stddevs[i].append(sw.stddev())

            logger.info(u'%76s: %s', participant.name, sw)
        last_fn = fn

    return means, stddevs
1104251
@Benchmark
    public Class<?> benchmarkByteBuddy() {
        return new ByteBuddy()
                .with(TypeValidation.DISABLED)
                .ignore(any())
                .subclass(baseClass)
                .make()
                .load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION)
                .getLoaded();
    }