copied from zend to insert benchmark checkpoints
506466
public function dispatch($action)
    {
        // Notify helpers of action preDispatch state
        $this->_helper->notifyPreDispatch();

        $this->preDispatch();
        Kwf_Benchmark::checkpoint('Action::preDispatch');
        if ($this->getRequest()->isDispatched()) {
            if (null === $this->_classMethods) {
                $this->_classMethods = get_class_methods($this);
            }

            // preDispatch() didn't change the action, so we can continue
            if ($this->getInvokeArg('useCaseSensitiveActions') || in_array($action, $this->_classMethods)) {
                if ($this->getInvokeArg('useCaseSensitiveActions')) {
                    trigger_error('Using case sensitive actions without word separators is deprecated; please do not rely on this "feature"');
                }
                $this->$action();
            } else {
                $this->__call($action, array());
            }
            Kwf_Benchmark::checkpoint('Action::action');

            $this->postDispatch();
            Kwf_Benchmark::checkpoint('Action::postDispatch');
        }

        // whats actually important here is that this action controller is
        // shutting down, regardless of dispatching; notify the helpers of this
        // state
        $this->_helper->notifyPostDispatch();
    }
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)
775620
public function benchmark($caller, $record, string $context = '')
    {
        $benchmarkID = count($this->benchmarks);
        if (is_array($record)) {
            $benchmarkID = $record[0];
        } elseif (!isset($this->benchmarks[$benchmarkID])) {
            $this->benchmarks[$benchmarkID] = [$caller, $record, $context, microtime(true)];

            //Payload
            return [$benchmarkID];
        }

        if (!isset($this->benchmarks[$benchmarkID])) {
            throw new BenchmarkException("Unpaired benchmark record '{$benchmarkID}'");
        }

        $this->benchmarks[$benchmarkID][4] = microtime(true);

        return $this->benchmarks[$benchmarkID][4] - $this->benchmarks[$benchmarkID][3];
    }
652814
protected function seedMetricPoints()
    {
        MetricPoint::truncate();

        // Generate 11 hours of metric points
        for ($i = 0; $i < 11; $i++) {
            $metricTime = (new DateTime())->sub(new DateInterval('PT'.$i.'H'));

            MetricPoint::create([
                'metric_id'  => 1,
                'value'      => random_int(1, 10),
                'created_at' => $metricTime,
                'updated_at' => $metricTime,
            ]);
        }
    }
664483
protected final void checkPoints() {
        if (pointsDirty) {
            createPoints();
            findCenter();
            calculateRadius();
            
            if (points.length > 0) {
	            maxX = points[0];
	            maxY = points[1];
	            minX = points[0];
	            minY = points[1];
	            for (int i=0;i<points.length/2;i++) {
	            	maxX = Math.max(points[i*2],maxX);
	            	maxY = Math.max(points[(i*2)+1],maxY);
	            	minX = Math.min(points[i*2],minX);
	            	minY = Math.min(points[(i*2)+1],minY);
	            }
            }
            pointsDirty = false;
            trianglesDirty = true;
        }
    }
309457
def checkpoint_parameter_from_file(node_type, parameter)
      Bebox::Node.checkpoint_parameter_from_file(self.project_root, self.environment, self.hostname, node_type, parameter)
    end
1287136
private function benchmark(string $event, $context = null): Benchmark
    {
        $container = ContainerScope::getContainer();
        if (empty($container) || !$container->has(BenchmarkerInterface::class)) {
            return new Benchmark(
                get_class($this),
                $event,
                $context
            );
        }

        return $container->get(BenchmarkerInterface::class)->record(
            get_class($this),
            $event,
            $context
        );
    }
340256
def restore_checkpoint(ckpt_dir, saver, sess, must_restore=False):
  """"""
  ckpt = tf.train.get_checkpoint_state(ckpt_dir)
  if must_restore and not ckpt:
    raise ValueError("No checkpoint found in %s" % ckpt_dir)
  if not ckpt:
    return 0

  path = ckpt.model_checkpoint_path
  tf.logging.info("Restoring checkpoint %s", path)
  saver.restore(sess, path)
  step = int(path.split("-")[-1])
  return step
459892
public function benchmark($iterations = 10000, $inputSize = null)
    {
        $set = new BenchmarkResultsSet($iterations, $inputSize);
        $this->resultsGroup->addSet($set);

        foreach ($this->getSamplersForInputSize($inputSize) as $name => $func) {
            $actualIterations = $this->getActualIterations($name, $iterations, $inputSize);

            $start = microtime(true);
            for ($i = 0; $i < $actualIterations; $i++)
                $func();
            $time = microtime(true) - $start;

            $set->addBenchmark(new Benchmark($name, $time, $actualIterations));
        }

        return $this;
    }
141768
def step( self, peer_table=None, zonefile_queue=None, path=None ):
        
        if path is None:
            path = self.atlasdb_path

        if BLOCKSTACK_TEST:
            log.debug("%s: %s step" % (self.hostport, self.__class__.__name__))

        if self.push_timeout is None:
            self.push_timeout = atlas_push_zonefiles_timeout()

        zfinfo = atlas_zonefile_push_dequeue( zonefile_queue=zonefile_queue )
        if zfinfo is None:
            return 0

        zfhash = zfinfo['zonefile_hash']
        zfdata_txt = zfinfo['zonefile']
        name = zfinfo['name']
        txid = zfinfo['txid']

        zfbits = atlasdb_get_zonefile_bits( zfhash, path=path )
        if len(zfbits) == 0:
            # not recognized 
            return 0

        # it's a valid zonefile.  store it.
        rc = add_atlas_zonefile_data( str(zfdata_txt), self.zonefile_dir )
        if not rc:
            log.error("Failed to replicate zonefile %s to external storage" % zfhash)

        peers = None
        
        # see if we can send this somewhere
        with AtlasPeerTableLocked(peer_table) as ptbl:
            peers = atlas_zonefile_find_push_peers( zfhash, peer_table=ptbl, zonefile_bits=zfbits )

        if len(peers) == 0:
            # everyone has it
            log.debug("%s: All peers have zonefile %s" % (self.hostport, zfhash))
            return 0

        # push it off
        ret = 0
        for peer in peers:
            log.debug("%s: Push to %s" % (self.hostport, peer))
            atlas_zonefile_push( self.hostport, peer, zfdata_txt, timeout=self.push_timeout )
            ret += 1

        return ret
106160
def atlas_zonefile_push_enqueue( zonefile_hash, name, txid, zonefile_data, zonefile_queue=None, con=None, path=None ):
    
    res = False

    bits = atlasdb_get_zonefile_bits( zonefile_hash, path=path, con=con )
    if len(bits) == 0:
        # invalid hash
        return

    with AtlasZonefileQueueLocked(zonefile_queue) as zfq:

        if len(zfq) < MAX_QUEUED_ZONEFILES: 
            zfdata = {
                'zonefile_hash': zonefile_hash,
                'zonefile': zonefile_data,
                'name': name,
                'txid': txid
            }

            zfq.append( zfdata )
            res = True
    
    return res
1051926
def benchmark_process_and_backend(exe, backend):
    """"""
    env = dict(os.environ)
    env['GOLESS_BACKEND'] = backend
    args = [exe, '-m', 'benchmark']
    return get_benchproc_results(args, env=env)
955259
public function printBenchmarkSummary(Benchmark $benchmark, array $results)
    {
        $averagedResults = array_map(function ($result) {
                return array_sum($result) / count($result);
            }, $results);

        $template = "%s | %s | %s | %s | %s\n";
        asort($averagedResults);
        reset($averagedResults);
        $fastestResult = each($averagedResults);
        printf($template, "Test Name", "Results", "Time", "+ Interval", "Change");
        printf($template, "---------", "-------", "----", "----------", "------");
        foreach ($averagedResults as $name => $result) {
            $interval = $result - $fastestResult["value"];
            $change   = round((1 - $result / $fastestResult["value"]) * 100, 0);
            if ($change == 0) {
                $change = 'baseline';
            } else {
                $faster = true; // Cant really ever be faster, now can it
                if ($change < 0) {
                    $faster = false;
                    $change *= -1;
                }
                $change .= '% ' . ($faster ? 'faster' : 'slower');
            }
            printf(
                $template,
                $name,
                number_format(count($results[$name])),
                sprintf("%.10f", $result),
                "+" . sprintf("%.10f", $interval),
                $change
            );
        }
    }
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
1113985
def save_params(step_num, model, trainer, ckpt_dir):
    """"""
    param_path = os.path.join(ckpt_dir, '%07d.params'%step_num)
    trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num)
    logging.info('[step %d] Saving checkpoints to %s, %s.',
                 step_num, param_path, trainer_path)
    model.save_parameters(param_path)
    trainer.save_states(trainer_path)
485397
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);

        // preload keys if requested
        System.out.println();
        if (config.preload) {
            System.out.println("Preloading data store...");
            for(int i=0; i < config.poolsize; i++) {
                String keyStr = String.format(processor.KeyFormat, i);
                byte[] valArr = processor.generateForStore().getStoreValue();
                if (config.multisingleratio != 0.00) {
                    client.callProcedure(new NullCallback(),
                                         "STORER.upsert",
                                         keyStr,
                                         valArr);
                }
                client.callProcedure(new NullCallback(),
                                     "STORE.upsert",
                                     keyStr,
                                     valArr);
            }
            client.drain();
            System.out.println("Preloading complete.\n");
        }

        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()) {
            // Decide whether to perform a GET or PUT operation
            if (rand.nextDouble() < config.getputratio) {
                // Get a key/value pair using inbuilt select procedure, asynchronously
                if (rand.nextDouble() < config.multisingleratio) {
                    client.callProcedure(new NullCallback(), "selectR", processor.generateRandomKeyForRetrieval());
                }
                else {
                    client.callProcedure(new NullCallback(), "STORE.select", processor.generateRandomKeyForRetrieval());
                }
            }
            else {
                String table = rand.nextDouble() < config.multisingleratio ? "STORER" : "STORE";
                // Put a key/value pair using inbuilt upsert procedure, asynchronously
                final PayloadProcessor.Pair pair = processor.generateForStore();
                client.callProcedure(new NullCallback(), table+".upsert", pair.Key, pair.getStoreValue());
            }
        }

        // 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()) {
            // Decide whether to perform a GET or PUT operation
            if (rand.nextDouble() < config.getputratio) {
                // Get a key/value pair using inbuilt select procedure, asynchronously
                if (rand.nextDouble() < config.multisingleratio) {
                    client.callProcedure(new GetCallback(), "selectR", processor.generateRandomKeyForRetrieval());
                }
                else {
                    client.callProcedure(new GetCallback(), "STORE.select", processor.generateRandomKeyForRetrieval());
                }
            }
            else {
                String table = rand.nextDouble() < config.multisingleratio ? "STORER" : "STORE";
                // Put a key/value pair using inbuilt upsert procedure, asynchronously
                final PayloadProcessor.Pair pair = processor.generateForStore();
                client.callProcedure(new PutCallback(pair), table+".upsert", pair.Key, pair.getStoreValue());
            }
        }

        // 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();
    }
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();
	}