Write a single function benchmark.

        Args:
            fb (FunctionBenchmark): FunctionBenchmark class instance.
                Before passing to this, you should call ``fb.benchmark()``.
338186
def write(self, fb):
        
        print('[{}.{}]'.format(fb.module, fb.func.__name__), file=self.file)
        print('class = {}'.format(fb.func_ins.name), file=self.file)
        print('inspecs = {}'.format(repr(fb.inspecs)), file=self.file)
        print('func_args = {}'.format(repr(fb.func_args)), file=self.file)
        print('func_kwargs = {}'.format(repr(fb.func_kwargs)), file=self.file)
        print('ext = ({}, {})'.format(
            repr(fb.ext), repr(fb.ext_kwargs)), file=self.file)
        if self.setup_stat is not None:
            self._write_a_stat('setup', self.setup_stat)
        if self.foward_stat is not None:
            self._write_a_stat('forward', self.forward_stat)
        if self.backward_stat is not None:
            self._write_a_stat('backward', self.backward_stat)
881463
function doSyncBench(fn, callback) {

		var start,
		    fnOverhead,
		    pretotal,
		    result,
		    runs,
		    name;

		runs = 0;

		// For the initial test, to determine how many iterations we should
		// test later, we just use Date.now()
		start = Date.now();

		// See how many times we can get it to run for 50ms
		// This doesn't need to be precise yet. We don't use these results
		// for the ops count because Date.now() takes time, too
		do {
			fn();
			runs++;
			pretotal = Date.now() - start;
		} while (pretotal < 50);

		// See how long it takes to run an empty function
		fnOverhead = getFunctionOverhead(runs);

		result = syncTest(fn, runs, fnOverhead);

		if (callback) {
			result.name = fn.name || '';
			callback(null, result);
		} else {
			name = fn.name || '';
			if (name) name = 'for "' + name + '" ';

			console.log('Benchmark ' + name + 'did ' + Bound.Number.humanize(result.ops) + '/s (' + Bound.Number.humanize(result.iterations) + ' iterations)');
		}

		return result;
	}
726005
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(config.servers);

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

        // reset the stats after warmup
        fullStatsContext.fetchAndResetBaseline();
        periodicStatsContext.fetchAndResetBaseline();

        // print periodic statistics to the console
        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 * config.duration);

        while (benchmarkEndTime > System.currentTimeMillis()) {
            long[] pair = generator.getNextAppIdAndUniqueDeviceId();
            int appId = (int) pair[0];
            long nextValue = pair[1];
            long hashedValue = MurmurHash.hash64(nextValue);

            client.callProcedure(new CountCallback(),
                                 "CountDeviceEstimate",
                                 appId,
                                 hashedValue);
        }

        // cancel periodic stats printing
        timer.cancel();

        // block until all outstanding txns return
        client.drain();

        // print the summary results
        printResults();

        // close down the client connections
        client.close();
    }
327586
function benchmark(fn, times, name){
	fn = fn.toString();
	var s = fn.indexOf('{')+1,
		e = fn.lastIndexOf('}');
	fn = fn.substring(s,e);

	return benchmarkString(fn, times, name);
}
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)
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();
	}
}
375290
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(config.servers);

        // initialize using synchronous call
        System.out.println("\nPopulating Static Tables\n");
        client.callProcedure("Initialize", config.contestants, CONTESTANT_NAMES_CSV);

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

        // Run the benchmark loop for the requested warmup time
        // The throughput may be throttled depending on client configuration
        System.out.println("Warming up...");
        final long warmupEndTime = System.currentTimeMillis() + (1000l * config.warmup);
        while (warmupEndTime > System.currentTimeMillis()) {
            // Get the next phone call
            PhoneCallGenerator.PhoneCall call = switchboard.receive();

            // asynchronously call the "Vote" procedure
            client.callProcedure(new NullCallback(),
                                 "Vote",
                                 call.phoneNumber,
                                 call.contestantNumber,
                                 config.maxvotes);
        }

        // reset the stats after warmup
        fullStatsContext.fetchAndResetBaseline();
        periodicStatsContext.fetchAndResetBaseline();

        // print periodic statistics to the console
        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 * config.duration);
        while (benchmarkEndTime > System.currentTimeMillis()) {
            // Get the next phone call
            PhoneCallGenerator.PhoneCall call = switchboard.receive();

            // asynchronously call the "Vote" procedure
            client.callProcedure(new VoterCallback(),
                                 "Vote",
                                 call.phoneNumber,
                                 call.contestantNumber,
                                 config.maxvotes);
        }

        // cancel periodic stats printing
        timer.cancel();

        // block until all outstanding txns return
        client.drain();

        // print the summary results
        printResults();

        // close down the client connections
        client.close();
    }
648116
public void setUpBenchmark(Object benchmarkInstance) throws UserCodeException {
    boolean setupSuccess = false;
    try {
      callSetUp(benchmarkInstance);
      setupSuccess = true;
    } finally {
      // If setUp fails, we should call tearDown. If this method throws an exception, we
      // need to call tearDown from here, because no one else has the reference to the
      // Benchmark.
      if (!setupSuccess) {
        callTearDown(benchmarkInstance);
      }
    }
  }
885312
def run(self, **kwargs):
        '''
        
        '''
        self.report_start()
        for bench in self.benchmarks:
            bench = bench(before=self.report_before_method,
                      after=self.report_after_method,
                      after_each=self.report_progress,
                      debug=self.debug,
                      **kwargs)
            self.report_before_class(bench)
            bench.run()
            self.report_after_class(bench)
            self.runned.append(bench)
        self.report_end()
1049582
function createFunction() {
      // Lazy define.
      createFunction = function(args, body) {
        var result,
            anchor = freeDefine ? freeDefine.amd : Benchmark,
            prop = uid + 'createFunction';

        runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}');
        result = anchor[prop];
        delete anchor[prop];
        return result;
      };
      // Fix JaegerMonkey bug.
      // For more information see http://bugzil.la/639720.
      createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function;
      return createFunction.apply(null, arguments);
    }
1175630
def profile(func):
    
    @inlineCallbacks
    def callme(*args, **kwargs):
        start = time.time()
        ret = yield func(*args, **kwargs)
        time_to_execute = time.time() - start
        log.msg('%s executed in %.3f seconds' % (func.__name__, time_to_execute))
        returnValue(ret)
    return callme
1046376
def benchmark(args):
    
    p = OptionParser(benchmark.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    pf, bedfile = args
    truth = pf + ".truth"
    synfind = pf + ".synfind"
    mcscanx = pf + ".mcscanx"
    iadhore = pf + ".iadhore"
    orthofinder = pf + ".orthofinder"
    pivots = set([x.accn for x in Bed(bedfile)])

    fp = open(truth)
    truth = set()
    for row in fp:
        a, b = row.strip().split("\t")[:2]
        pivots.add(a)
        truth.add(tuple(sorted((a, b))))
    logging.debug("Truth: {0} pairs".format(len(truth)))

    fp = open(synfind)
    benchmarkfile = pf + ".benchmark"
    fw = must_open(benchmarkfile, "w")
    synfind = set()
    for row in fp:
        atoms = row.strip().split("\t")
        query, hit, tag = atoms[:3]
        if tag != "S":
            continue
        synfind.add(tuple(sorted((query, hit))))
    calc_sensitivity_specificity(synfind, truth, "SynFind", fw)

    fp = open(mcscanx)
    mcscanx = set()
    for row in fp:
        if row[0] == '#':
            continue
        atoms = row.strip().split(":")[1].split()
        query, hit = atoms[:2]
        mcscanx.add(tuple(sorted((query, hit))))
    calc_sensitivity_specificity(mcscanx, truth, "MCScanX", fw)

    fp = open(iadhore)
    iadhore = set()
    next(fp)
    for row in fp:
        atoms = row.strip().split("\t")
        query, hit = atoms[3:5]
        iadhore.add(tuple(sorted((query, hit))))
    calc_sensitivity_specificity(iadhore, truth, "iADHoRe", fw)

    fp = open(orthofinder)
    orthofinder = set()
    next(fp)
    for row in fp:
        row = row.replace('"', "")
        atoms = row.replace(",", " ").split()
        genes = [x.strip() for x in atoms if not x.startswith("OG")]
        genes = [gene_name(x) for x in genes]
        pps = [x for x in genes if x in pivots]
        for p in pps:
            for g in genes:
                if p == g:
                    continue
                orthofinder.add(tuple(sorted((p, g))))
    #write_pairs(orthofinder, "orthofinder.pairs")
    calc_sensitivity_specificity(orthofinder, truth, "OrthoFinder", fw)
    fw.close()
968601
def disc_benchmarks(root, ignore_import_errors=False):
    

    root_name = os.path.basename(root)

    for module in disc_modules(root_name, ignore_import_errors=ignore_import_errors):
        for attr_name, module_attr in (
            (k, v) for k, v in module.__dict__.items()
            if not k.startswith('_')
        ):
            if inspect.isclass(module_attr):
                for name, class_attr in inspect.getmembers(module_attr):
                    if (inspect.isfunction(class_attr) or
                            inspect.ismethod(class_attr)):
                        benchmark = _get_benchmark(name, module, module_attr,
                                                   class_attr)
                        if benchmark is not None:
                            yield benchmark
            elif inspect.isfunction(module_attr):
                benchmark = _get_benchmark(attr_name, module, None, module_attr)
                if benchmark is not None:
                    yield benchmark
612998
public void startBenchmark() {
    startTime = System.currentTimeMillis();
    LOG.info("Start to benchmark chronos server");

    Thread t = new Thread() { // new thread to output the metrics
      @Override
      public void run() {
        final long collectPeriod = 10000;
        LOG.info("Start another thread to export benchmark metrics every " + collectPeriod / 1000.0
            + " second");

        int totalCount;
        int totalLatency;
        long exportTime;
        int lastTotalCount = 0;
        int lastTotalLatency = 0;
        long lastExportTime = startTime;

        while (true) {
          try {
            Thread.sleep(collectPeriod);
          } catch (InterruptedException e) {
            LOG.error("Interrupt when sleep to get benchmark metrics, exit immediately");
            System.exit(0);
          }

          exportTime = System.currentTimeMillis();
          totalCount = totalCountInteger.get();
          totalLatency = totalLatencyInteger.get();

          double totalCostTime = (exportTime - startTime) / 1000.0;
          double costTime = (exportTime - lastExportTime) / 1000.0;
          double qps = (totalCount - lastTotalCount) / costTime;
          double latency = (totalLatency - lastTotalLatency) * 1.0 / (totalCount - lastTotalCount);
          System.out.println("Total " + totalCostTime + ", in " + costTime + " seconds, qps: "
              + qps + ", latency: " + latency + "ms");

          lastTotalCount = totalCount;
          lastTotalLatency = totalLatency;
          lastExportTime = exportTime;
        }
      }
    };

    t.setDaemon(true);
    t.start();

    while (true) {
      try {
        long start = System.currentTimeMillis();
        currentTimestamp = chronosClient.getTimestamp();
        totalCountInteger.incrementAndGet();
        totalLatencyInteger.addAndGet((int) (System.currentTimeMillis() - start));

        if (currentTimestamp <= previousTimestamp) { // check correctness
          LOG.error("Fatal error to get a lower timestamp " + currentTimestamp + "(previous is "
              + previousTimestamp + "), exit immediately");
          System.exit(0);
        }
        previousTimestamp = currentTimestamp;

        if (isFailover == true) { // calculate failover time
          double failoverTime = (System.currentTimeMillis() - failoverStartTime) / 1000.0;
          System.out.println("After " + failoverStartTimeString + ", the total failover time is "
              + failoverTime + " seconds");
        }
        isFailover = false;
      } catch (IOException e) {
        LOG.error("Exception to get timestamp");

        if (isFailover == false) {
          failoverStartTime = System.currentTimeMillis();
          failoverStartTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(
              failoverStartTime));
          LOG.info("Failover occurs at " + failoverStartTimeString);
        }
        isFailover = true;
      }
    }

  }
408073
def write(self, fn=None):
        """"""
        fn = fn or self.fn
        if not os.path.exists(os.path.dirname(fn)):
            os.makedirs(os.path.dirname(fn))
        f = open(self.fn, 'rb')
        b = f.read()
        f.close()
        f = open(fn, 'wb')
        f.write(b)
        f.close()
483741
def write(self, fptr):
        
        self._write_validate()
        length = 15 if self.icc_profile is None else 11 + len(self.icc_profile)
        fptr.write(struct.pack('>I4s', length, b'colr'))

        read_buffer = struct.pack('>BBBI',
                                  self.method,
                                  self.precedence,
                                  self.approximation,
                                  self.colorspace)
        fptr.write(read_buffer)
351031
def log_benchmark(fn, start, end):
    
    elapsed = round(end - start, 2)
    line = ("Benchmark - Function: {} , Time: {} seconds".format(fn, elapsed))
    return line