Setup a custom benchmark handler or let zipline manage it
189845
def _get_benchmark_handler(self, last_trade, freq='minutely'):
        '''
        
        '''
        return LiveBenchmark(
            last_trade, frequency=freq).surcharge_market_data \
            if utils.is_live(last_trade) else None
464841
def run():
    
    # GLOBALS
    global cwd, files, logger_start, logger_benchmark, settings, _timeseries_data
    _timeseries_data = {}
    # files = {".lpd": [ {"full_path", "filename_ext", "filename_no_ext", "dir"} ], ".xls": [...], ".txt": [...]}
    settings = {"note_update": True, "note_validate": True, "verbose": True}
    cwd = os.getcwd()
    # logger created in whatever directory lipd is called from
    logger_start = create_logger("start")
    logger_benchmark = create_benchmark("benchmarks", "benchmark.log")
    files = {".txt": [], ".lpd": [], ".xls": []}

    return
680528
def setup(app: Application,
          tracer: Tracer, *,
          skip_routes: Optional[AbstractRoute] = None,
          tracer_key: str = APP_AIOZIPKIN_KEY,
          request_key: str = REQUEST_AIOZIPKIN_KEY) -> Application:
    
    app[tracer_key] = tracer
    m = middleware_maker(skip_routes=skip_routes,
                         tracer_key=tracer_key,
                         request_key=request_key)
    app.middlewares.append(m)

    # register cleanup signal to close zipkin transport connections
    async def close_aiozipkin(app: Application) -> None:
        await app[tracer_key].close()

    app.on_cleanup.append(close_aiozipkin)

    return app
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)
863639
def cli(env):
    """"""
    mgr = SoftLayer.LoadBalancerManager(env.client)

    routing_methods = mgr.get_routing_methods()
    table = formatting.KeyValueTable(['ID', 'Name'])
    table.align['ID'] = 'l'
    table.align['Name'] = 'l'
    table.sortby = 'ID'
    for routing_method in routing_methods:
        table.add_row([routing_method['id'], routing_method['name']])

    env.fout(table)
823306
def main(argv=None):
    """"""
    parser = argparse.ArgumentParser(description="Benchmark driver")

    parser.add_argument("--max-records", type=int, default=100 * 1000)
    parser.add_argument("--engine", type=str, choices=("vcfpy", "pyvcf"), default="vcfpy")
    parser.add_argument("--input-vcf", type=str, required=True, help="Path to VCF file to read")
    parser.add_argument(
        "--output-vcf", type=str, required=False, help="Path to VCF file to write if given"
    )

    args = parser.parse_args(argv)
    if args.engine == "vcfpy":
        VCFPyRunner(args).run()
    else:
        PyVCFRunner(args).run()
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)
199934
def _process_batch(self, param, dataframe):
        
        now = time.time()
        if param.eval_metric is not None:
            metrics = dict(param.eval_metric.get_name_value())
            param.eval_metric.reset()
        else:
            metrics = {}
        # #11504
        try:
            speed = self.frequent / (now - self.last_time)
        except ZeroDivisionError:
            speed = float('inf')
        metrics['batches_per_sec'] = speed * self.batch_size
        metrics['records_per_sec'] = speed
        metrics['elapsed'] = self.elapsed()
        metrics['minibatch_count'] = param.nbatch
        metrics['epoch'] = param.epoch
        self.append_metrics(metrics, dataframe)
        self.last_time = now
769765
def lambda_handler(event, context, settings_name="zappa_settings"):
    
    # Loading settings from a python module
    settings = importlib.import_module(settings_name)

    # The flask-app module
    app_module = importlib.import_module(settings.APP_MODULE)

    # The flask-app
    app = getattr(app_module, settings.APP_OBJECT)
    app.config.from_object('zappa_settings')

    app.wsgi_app = ZappaWSGIMiddleware(app.wsgi_app)

    # This is a normal HTTP request
    if event.get('method', None):
        # If we just want to inspect this,
        # return this event instead of processing the request
        # https://your_api.aws-api.com/?event_echo=true
        event_echo = getattr(settings, "EVENT_ECHO", True)
        if event_echo:
            if 'event_echo' in list(event['params'].values()):
                return {'Content': str(event) + '\n' + str(context), 'Status': 200}

        # TODO: Enable Let's Encrypt
        # # If Let's Encrypt is defined in the settings,
        # # and the path is your.domain.com/.well-known/acme-challenge/{{lets_encrypt_challenge_content}},
        # # return a 200 of lets_encrypt_challenge_content.
        # lets_encrypt_challenge_path = getattr(settings, "LETS_ENCRYPT_CHALLENGE_PATH", None)
        # lets_encrypt_challenge_content = getattr(settings, "LETS_ENCRYPT_CHALLENGE_CONTENT", None)
        # if lets_encrypt_challenge_path:
        #     if len(event['params']) == 3:
        #         if event['params']['parameter_1'] == '.well-known' and \
        #             event['params']['parameter_2'] == 'acme-challenge' and \
        #             event['params']['parameter_3'] == lets_encrypt_challenge_path:
        #                 return {'Content': lets_encrypt_challenge_content, 'Status': 200}

        # Create the environment for WSGI and handle the request
        environ = create_wsgi_request(event, script_name=settings.SCRIPT_NAME,
                                      trailing_slash=False)

        # We are always on https on Lambda, so tell our wsgi app that.
        environ['wsgi.url_scheme'] = 'https'

        response = Response.from_app(app, environ)

        # This doesn't work. It should probably be set right after creation, not
        # at such a late stage.
        # response.autocorrect_location_header = False

        zappa_returndict = dict()

        if response.data:
            zappa_returndict['Content'] = response.data

        # Pack the WSGI response into our special dictionary.
        for (header_name, header_value) in response.headers:
            zappa_returndict[header_name] = header_value
        zappa_returndict['Status'] = response.status_code

        # TODO: No clue how to handle the flask-equivalent of this. Or is this
        # something entirely specified by the middleware?
        # # Parse the WSGI Cookie and pack it.
        # cookie = response.cookies.output()
        # if ': ' in cookie:
        #     zappa_returndict['Set-Cookie'] = response.cookies.output().split(': ')[1]

        # To ensure correct status codes, we need to
        # pack the response as a deterministic B64 string and raise it
        # as an error to match our APIGW regex.
        # The DOCTYPE ensures that the page still renders in the browser.
        if response.status_code in [400, 401, 403, 404, 500]:
            content = "<!DOCTYPE html>" + str(response.status_code) + response.data
            b64_content = base64.b64encode(content)
            raise Exception(b64_content)
        # Internal are changed to become relative redirects
        # so they still work for apps on raw APIGW and on a domain.
        elif response.status_code in [301, 302]:
            # Location is by default relative on Flask. Location is by default
            # absolute on Werkzeug. We can set autocorrect_location_header on
            # the response to False, but it doesn't work. We have to manually
            # remove the host part.
            location = response.location
            hostname = 'https://' + environ['HTTP_HOST']
            if location.startswith(hostname):
                location = location[len(hostname):]
            raise Exception(location)
        else:
            return zappa_returndict
492326
def call!(env)
      env['rack.logger'] = @logger

      status, headers, body = nil, nil, nil
      benchmark = Benchmark.measure do
        status, headers, body = @app.call(env)
      end
      log_error(env['deas.error'])
      env['deas.time_taken'] = RoundedTime.new(benchmark.real)

      [status, headers, body]
    end
1117109
def setup_handler(context):
    

    if context.readDataFile("bika.lims_various.txt") is None:
        return

    logger.info(" [BEGIN]")

    portal = context.getSite()

    # Run Installers
    remove_default_content(portal)
    hide_navbar_items(portal)
    reindex_content_structure(portal)
    setup_groups(portal)
    setup_catalog_mappings(portal)
    setup_core_catalogs(portal)

    # Setting up all LIMS catalogs defined in catalog folder
    setup_catalogs(portal, getCatalogDefinitions())

    # Run after all catalogs have been setup
    setup_auditlog_catalog(portal)

    logger.info(" [DONE]")
728485
def benchmark_method(f):
    ""
    @wraps(f)
    def inner(name, *args, **kwargs):
        return Benchmark(name, f, args, kwargs)
    return inner
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()
753453
async function* run_table_cases(worker, data, test) {
    console.log(`Benchmarking \`${test}\``);
    try {
        for (let x = 0; x < ITERATIONS + TOSS_ITERATIONS; x++) {
            const start = performance.now();
            const table = worker.table(data.slice ? data.slice() : data);
            await table.size();
            if (x >= TOSS_ITERATIONS) {
                yield {
                    test,
                    time: performance.now() - start,
                    method: test,
                    row_pivots: "n/a",
                    column_pivots: "n/a",
                    aggregate: "n/a"
                };
            }
            await table.delete();
        }
    } catch (e) {
        console.error(`Benchmark ${test} failed`, e);
    }
}
848431
def optimize_structure_handler(rule, handler):
    

    def runner(walk, dispatcher, node):
        handler(dispatcher, node)
        return
        yield  # pragma: no cover

    return runner
871295
def lambda_handler(event, context=None, settings_name="zappa_settings"):  # NoQA
    
    time_start = datetime.datetime.now()

    # If in DEBUG mode, log all raw incoming events.
    if settings.DEBUG:
        logger.info('Zappa Event: {}'.format(event))

    # This is a normal HTTP request
    if event.get('method', None):

        # Create the environment for WSGI and handle the request
        environ = create_wsgi_request(event, script_name=settings.SCRIPT_NAME)

        # We are always on https on Lambda, so tell our wsgi app that.
        environ['HTTPS'] = 'on'
        environ['wsgi.url_scheme'] = 'https'

        wrap_me = get_wsgi_application()
        app = ZappaWSGIMiddleware(wrap_me)

        # Execute the application
        response = Response.from_app(app, environ)
        response.content = response.data

        # Prepare the special dictionary which will be returned to the API GW.
        returnme = {'Content': response.data}

        # Pack the WSGI response into our special dictionary.
        for (header_name, header_value) in response.headers:
            returnme[header_name] = header_value
        returnme['Status'] = response.status_code

        # To ensure correct status codes, we need to
        # pack the response as a deterministic B64 string and raise it
        # as an error to match our APIGW regex.
        # The DOCTYPE ensures that the page still renders in the browser.
        exception = None
        if response.status_code in ERROR_CODES:
            content = u"<!DOCTYPE html>" + unicode(response.status_code) + unicode('<meta charset="utf-8" />') + response.data.encode('utf-8')
            b64_content = base64.b64encode(content)
            exception = (b64_content)
        # Internal are changed to become relative redirects
        # so they still work for apps on raw APIGW and on a domain.
        elif 300 <= response.status_code < 400 and response.has_header('Location'):
            location = returnme['Location']
            location = '/' + location.replace("http://zappa/", "")
            exception = location

        # Calculate the total response time,
        # and log it in the Common Log format.
        time_end = datetime.datetime.now()
        delta = time_end - time_start
        response_time_ms = delta.total_seconds() * 1000
        common_log(environ, response, response_time=response_time_ms)

        # Finally, return the response to API Gateway.
        if exception:
            raise Exception(exception)
        else:
            return returnme

    # This is a management command invocation.
    elif event.get('command', None):
        from django.core import management

        # Couldn't figure out how to get the value into stdout with StringIO..
        # Read the log for now. :[]
        management.call_command(*event['command'].split(' '))
        return {}
    elif event.get('detail'):
        module, function = event['detail'].rsplit('.', 1)

        app_module = importlib.import_module(module)
        app_function = getattr(app_module, function)

        # Execute the function!
        app_function()
        return
    else:
        logger.error('Unhandled event: {}'.format(json.dumps(event)))
727806
public static void runWith(
      String[] args, Function<BenchmarkSettings, SmCodecBenchmarkState> benchmarkStateFactory) {

    BenchmarkSettings settings =
        BenchmarkSettings.from(args).durationUnit(TimeUnit.NANOSECONDS).build();

    SmCodecBenchmarkState benchmarkState = benchmarkStateFactory.apply(settings);

    benchmarkState.runForSync(
        state -> {
          BenchmarkTimer timer = state.timer("timer");
          BenchmarkMeter meter = state.meter("meter");
          ServiceMessageCodec messageCodec = state.messageCodec();
          ServiceMessage message = state.messageWithByteBuf();

          return i -> {
            Context timeContext = timer.time();
            Object result =
                messageCodec.encodeAndTransform(
                    message,
                    (dataByteBuf, headersByteBuf) -> {
                      ReferenceCountUtil.release(headersByteBuf);
                      return dataByteBuf;
                    });
            timeContext.stop();
            meter.mark();
            return result;
          };
        });
  }