Useful for triggering a subset of the benchmark in a profiler.
1364
public static void main(String[] argv) throws Exception {
    StreamingResponseBandwidthBenchmark bench = new StreamingResponseBandwidthBenchmark();
    bench.setup();
    Thread.sleep(30000);
    bench.teardown();
    System.exit(0);
  }
1285864
def enable_thread_profiling(profile_dir, exception_callback=None):
    
    global profiled_thread_enabled, Thread, Process
    if os.path.isdir(profile_dir):
        _Profiler.profile_dir = profile_dir
    else:
        raise OSError('%s does not exist' % profile_dir)
    _Profiler.exception_callback = exception_callback
    Thread = threading.Thread = ProfiledThread
    Process = multiprocessing.Process = ProfiledProcess
    profiled_thread_enabled = True
395829
async function measure(test, bench) {
  let {
    delay,
    minTime,
    minSamples,
    minWarmups,
    onCycle,
    onSample,
  } = bench.config
  let { name, run } = test

  delay *= 1e3
  minTime *= 1e3

  let samples = []
  let cycle = {
    name, // test name
    hz: null, // samples per second
    size: null, // number of samples
    time: null, // elapsed time (including delays)
    stats: null,
  }

  let n = 0
  let t = process.hrtime()
  let warmups = -1

  // synchronous test
  if (run.length == 0) {
    let start
    while (true) {
      bench.before.forEach(call)
      if (test.before) test.before()

      start = process.hrtime()
      run()
      let sample = clock(start)

      if (test.after) test.after()
      bench.after.forEach(call)

      if (warmups == -1) {
        warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50)
      }
      if (warmups > 0) {
        warmups--
      } else {
        samples[n++] = sample
        onSample(samples[n - 1], cycle)

        if (minTime <= clock(t) && minSamples <= n) {
          break // all done!
        }
      }

      // wait then repeat
      await wait(delay)
    }
  }

  // asynchronous test
  else {
    let start
    const next = function() {
      bench.before.forEach(call)
      if (test.before) test.before()

      start = process.hrtime()
      run(done)
    }

    // called by the test function for every sample
    const done = function() {
      let sample = clock(start)

      if (test.after) test.after()
      bench.after.forEach(call)

      if (warmups == -1) {
        warmups = Math.max(minWarmups, sample > 100 ? 1 : sample > 10 ? 5 : 50)
      }
      if (warmups > 0) {
        warmups--
      } else {
        samples[n++] = sample
        onSample(samples[n - 1], cycle)

        if (minTime <= clock(t) && minSamples <= n) {
          return cycle.done() // all done!
        }
      }

      // wait then repeat
      wait(delay).then(next)
    }

    defer(cycle) // wrap cycle with a promise
    next() // get the first sample

    // wait for samples
    await cycle.promise
  }

  const time = clock(t)
  const stats = analyze(samples)
  cycle.hz = 1000 / stats.mean
  cycle.size = n
  cycle.time = time
  cycle.stats = stats

  onCycle(cycle, bench.config)
}
1321530
function benchBatch(targets, cb, idx) {
  idx |= 0;
  if (targets.length == 0) return cb(idx);

  var target = targets.shift();
  process.stdout.write(util.format('[%s] ', idx+1));
  try {
    main.bench(target.name, target.func);
    idx++;
  } catch (err) {
    console.log('%s failed!', target.name);
  }

  //No more targets, no need to wait
  if (targets.length == 0) return cb(idx);

  //We need to wait some seconds before the next test,
  //or the results could vary depending on the order
  setTimeout(function() {
    benchBatch(targets, cb, idx); //Yeah, recursivity...
  }, 10000);
}
861161
def default_profiler(f, _type, _value):
    ''' 
    '''
    try:
        profile_print(
            '\n'.join([
                get_frame_src(f),
                get_locals(f),
                '----------------------------------------'
            ])
        )
    except:
        pass
299874
function Profiler(logger, name, level) {
  this.logger = logger;
  this.name = name;
  this.times = 0;
  this.diff = 0;
  this.paused = true;
  this.level = level || 'debug';
}
1285309
function toggleProfiler() {
			if (!data.profiler.show) {
				profilerCanvas.style.display = "block";
				profilerCheckBox.checked = true;
			} else {
				profilerCanvas.style.display = "none";
				profilerCheckBox.checked = false;
			}
			data.profiler.show = !data.profiler.show;
		}
406028
def matches_sample(output, target, threshold, is_correct, actual_output):
        
        return (bool(output > threshold) == bool(target)) == is_correct and actual_output == bool(output > threshold)
1305985
def profiling(self):
        
        self._log_profiler_started()
        while self.clients:
            try:
                self.profiler.start()
            except RuntimeError:
                pass
            # should sleep.
            yield
            self.profiler.stop()
            result = self.profiler.result()
            data = pack_msg(RESULT, result,
                            pickle_protocol=self.pickle_protocol)
            self._latest_result_data = data
            # broadcast.
            closed_clients = []
            for client in self.clients:
                try:
                    self._send(client, data)
                except socket.error as exc:
                    if exc.errno == EPIPE:
                        closed_clients.append(client)
            del data
            # handle disconnections.
            for client in closed_clients:
                self.disconnected(client)
        self._log_profiler_stopped()
1157481
def StartTiming(self, profile_name):
    
    if profile_name not in self._profile_measurements:
      self._profile_measurements[profile_name] = CPUTimeMeasurement()

    self._profile_measurements[profile_name].SampleStart()
100226
def _trigger(self):
        
        if len(self._stat_now):
            self._stat_now['epoch_num'] = self.epoch_num
            self._stat_now['global_step'] = self.global_step

            self._stats.append(self._stat_now)
            self._stat_now = {}
            self._write_stat()
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)
17633
function () {
    ++this.count;
    if (this.t0 === null) {
      this.start();
      return;
    }
    var elapsed = this._elapsed();
    if (elapsed > 1) {
      Profiler.new_value(this.name, this.count);
      this.count = 0;
      this.start();
    }
  }
1151378
public synchronized void startCollecting() {
		paused = false;
		if (thread != null)
			return;

		packages = new CountMap<String>(MAX_PACKAGES);
		selfMethods = new CountMap<String>(MAX_METHODS);
		stackMethods = new CountMap<String>(MAX_METHODS);
		lines = new CountMap<String>(MAX_LINES);
		total = 0;

		started = true;
		thread = new Thread(this);
		thread.setName("Profiler");
		thread.setDaemon(true);
		thread.start();
	}
507867
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();
	}
95037
def validate(self, benchmarks):
        
        class_code = self.setup_src
        instance_creation = '\ninstance = {}'.format(self.stmt)
        for i, benchmark in enumerate(benchmarks):
            if not benchmark.result_validation:
                break

            validation_code = class_code + instance_creation + '\nvalidation_result = ' + benchmark.stmt
            validation_scope = {}
            exec(validation_code, validation_scope)
            # Store the result in the first function in the group.
            if i == 0:
                compare_against_function = benchmarks[0].callable.__name__
                compare_against_result = validation_scope['validation_result']
                logging.info('PyPerform: Validating group "{b.group}" against method '
                             '"{b.classname}.{b.callable.__name__}"'.format(b=benchmarks[0]))
            else:
                if compare_against_result == validation_scope['validation_result']:
                    logging.info('PyPerform: Validating {b.classname}.{b.callable.__name__}......PASSED!'
                                 .format(b=benchmark))
                else:
                    error = 'Results of functions {0} and {1} are not equivalent.\n{0}:\t {2}\n{1}:\t{3}'
                    raise ValidationError(error.format(compare_against_function, benchmark.callable.__name__,
                                              compare_against_result, validation_scope['validation_result']))
1230105
def benchmark_command(cmd, progress):
    """"""
    full_cmd = '/usr/bin/time --format="%U %M" {0}'.format(cmd)
    print '{0:6.2f}% Running {1}'.format(100.0 * progress, full_cmd)
    (_, err) = subprocess.Popen(
        ['/bin/sh', '-c', full_cmd],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    ).communicate('')

    values = err.strip().split(' ')
    if len(values) == 2:
        try:
            return (float(values[0]), float(values[1]))
        except:  # pylint:disable=I0011,W0702
            pass  # Handled by the code after the "if"

    print err
    raise Exception('Error during benchmarking')