A simple command-line interface for the runexecutor module of BenchExec.
778443
def main(argv=None):
    
    if argv is None:
        argv = sys.argv

    # parse options
    parser = argparse.ArgumentParser(
        fromfile_prefix_chars='@',
        description=
        """Execute a command with resource limits and measurements.
           Command-line parameters can additionally be read from a file if file name prefixed with '@' is given as argument.
           Part of BenchExec: https://github.com/sosy-lab/benchexec/""")

    resource_args = parser.add_argument_group("optional arguments for resource limits")
    resource_args.add_argument("--memlimit", type=util.parse_memory_value, metavar="BYTES",
        help="memory limit in bytes")
    resource_args.add_argument("--timelimit", type=util.parse_timespan_value, metavar="SECONDS",
        help="CPU time limit in seconds")
    resource_args.add_argument("--softtimelimit", type=util.parse_timespan_value, metavar="SECONDS",
        help='"soft" CPU time limit in seconds (command will be send the TERM signal at this time)')
    resource_args.add_argument("--walltimelimit", type=util.parse_timespan_value, metavar="SECONDS",
        help='wall time limit in seconds (default is CPU time limit plus a few seconds)')
    resource_args.add_argument("--cores", type=util.parse_int_list, metavar="N,M-K",
        help="list of CPU cores to use")
    resource_args.add_argument("--memoryNodes", type=util.parse_int_list, metavar="N,M-K",
        help="list of memory nodes to use")

    io_args = parser.add_argument_group("optional arguments for run I/O")
    io_args.add_argument("--input", metavar="FILE",
        help="name of file used as stdin for command "
            "(default: /dev/null; use - for stdin passthrough)")
    io_args.add_argument("--output", default="output.log", metavar="FILE",
        help="name of file where command output (stdout and stderr) is written")
    io_args.add_argument("--maxOutputSize", type=util.parse_memory_value, metavar="BYTES",
        help="shrink output file to approximately this size if necessary "
            "(by removing lines from the middle of the output)")
    io_args.add_argument("--filesCountLimit", type=int, metavar="COUNT",
        help="maximum number of files the tool may write to (checked periodically, counts only files written in container mode or to temporary directories, only supported with --no-tmpfs)")
    io_args.add_argument("--filesSizeLimit", type=util.parse_memory_value, metavar="BYTES",
        help="maximum size of files the tool may write (checked periodically, counts only files written in container mode or to temporary directories, only supported with --no-tmpfs)")
    io_args.add_argument("--skip-cleanup", action="store_false", dest="cleanup",
        help="do not delete files created by the tool in temp directory")

    container_args = parser.add_argument_group("optional arguments for run container")
    container_on_args = container_args.add_mutually_exclusive_group()
    container_on_args.add_argument("--container", action='store_true',
        help="force isolation of run in container (future default starting with BenchExec 2.0)")
    container_on_args.add_argument("--no-container", action='store_true',
        help="disable use of containers for isolation of runs (current default)")
    containerexecutor.add_basic_container_args(container_args)
    containerexecutor.add_container_output_args(container_args)

    environment_args = parser.add_argument_group("optional arguments for run environment")
    environment_args.add_argument("--require-cgroup-subsystem", action="append", default=[], metavar="SUBSYSTEM",
        help="additional cgroup system that should be enabled for runs "
            "(may be specified multiple times)")
    environment_args.add_argument("--set-cgroup-value", action="append", dest="cgroup_values", default=[],
        metavar="SUBSYSTEM.OPTION=VALUE",
        help="additional cgroup values that should be set for runs (e.g., 'cpu.shares=1000')")
    environment_args.add_argument("--dir", metavar="DIR",
        help="working directory for executing the command (default is current directory)")
    environment_args.add_argument("--user", metavar="USER",
        help="execute tool under given user account (needs password-less sudo setup, "
            "not supported in combination with --container)")

    baseexecutor.add_basic_executor_options(parser)

    options = parser.parse_args(argv[1:])
    baseexecutor.handle_basic_executor_options(options, parser)

    if options.container:
        if options.user is not None:
            sys.exit("Cannot use --user in combination with --container.")
        container_options = containerexecutor.handle_basic_container_args(options, parser)
        container_output_options = containerexecutor.handle_container_output_args(options, parser)
        if container_options['container_tmpfs'] and (options.filesCountLimit or options.filesSizeLimit):
            parser.error("Files-count limit and files-size limit are not supported if tmpfs is used in container. Use --no-tmpfs to make these limits work or disable them (typically they are unnecessary if a tmpfs is used).")
    else:
        container_options = {}
        container_output_options = {}
        if options.user is not None:
            logging.warning(
                "Executing benchmarks at another user with --user is deprecated and may be removed in the future. "
                "Consider using the container mode instead for isolating runs "
                "(cf. https://github.com/sosy-lab/benchexec/issues/215).")
        elif not options.no_container:
            logging.warning(
                "Neither --container or --no-container was specified, "
                "not using containers for isolation of runs. "
                "Either specify --no-container to silence this warning, "
                "or specify --container to use containers for better isolation of runs "
                "(this will be the default starting with BenchExec 2.0). "
                "Please read https://github.com/sosy-lab/benchexec/blob/master/doc/container.md "
                "for more information.")

    # For integrating into some benchmarking frameworks,
    # there is a DEPRECATED special mode
    # where the first and only command-line argument is a serialized dict
    # with additional options
    env = {}
    if len(options.args) == 1 and options.args[0].startswith("{"):
        data = eval(options.args[0])
        options.args = data["args"]
        env = data.get("env", {})
        options.debug = data.get("debug", options.debug)
        if "maxLogfileSize" in data:
            try:
                options.maxOutputSize = int(data["maxLogfileSize"]) * _BYTE_FACTOR * _BYTE_FACTOR # MB to bytes
            except ValueError:
                options.maxOutputSize = util.parse_memory_value(data["maxLogfileSize"])

    if options.input == '-':
        stdin = sys.stdin
    elif options.input is not None:
        if options.input == options.output:
            parser.error("Input and output files cannot be the same.")
        try:
            stdin = open(options.input, 'rt')
        except IOError as e:
            parser.error(e)
    else:
        stdin = None

    cgroup_subsystems = set(options.require_cgroup_subsystem)
    cgroup_values = {}
    for arg in options.cgroup_values:
        try:
            key, value = arg.split("=", 1)
            subsystem, option = key.split(".", 1)
            if not subsystem or not option:
                raise ValueError()
        except ValueError:
            parser.error(
                'Cgroup value "{}" has invalid format, needs to be "subsystem.option=value".'
                    .format(arg))
        cgroup_values[(subsystem, option)] = value
        cgroup_subsystems.add(subsystem)

    executor = RunExecutor(user=options.user, cleanup_temp_dir=options.cleanup,
                           additional_cgroup_subsystems=list(cgroup_subsystems),
                           use_namespaces=options.container, **container_options)

    # ensure that process gets killed on interrupt/kill signal
    def signal_handler_kill(signum, frame):
        executor.stop()
    signal.signal(signal.SIGTERM, signal_handler_kill)
    signal.signal(signal.SIGINT,  signal_handler_kill)

    formatted_args = " ".join(map(util.escape_string_shell, options.args))
    logging.info('Starting command %s', formatted_args)
    if options.container and options.output_directory and options.result_files:
        logging.info('Writing output to %s and result files to %s',
                     util.escape_string_shell(options.output),
                     util.escape_string_shell(options.output_directory))
    else:
        logging.info('Writing output to %s', util.escape_string_shell(options.output))

    # actual run execution
    try:
        result = executor.execute_run(
                            args=options.args,
                            output_filename=options.output,
                            stdin=stdin,
                            hardtimelimit=options.timelimit,
                            softtimelimit=options.softtimelimit,
                            walltimelimit=options.walltimelimit,
                            cores=options.cores,
                            memlimit=options.memlimit,
                            memory_nodes=options.memoryNodes,
                            cgroupValues=cgroup_values,
                            environments=env,
                            workingDir=options.dir,
                            maxLogfileSize=options.maxOutputSize,
                            files_count_limit=options.filesCountLimit,
                            files_size_limit=options.filesSizeLimit,
                            **container_output_options)
    finally:
        if stdin:
            stdin.close()

    executor.check_for_new_files_in_home()

    # exit_code is a special number:
    exit_code = util.ProcessExitCode.from_raw(result['exitcode'])

    def print_optional_result(key, unit=''):
        if key in result:
            # avoid unicode literals such that the string can be parsed by Python 3.2
            print(key + "=" + str(result[key]).replace("'u", '') + unit)

    # output results
    print_optional_result('terminationreason')
    print("exitcode=" + str(exit_code.raw))
    if exit_code.value is not None:
        print("returnvalue=" + str(exit_code.value))
    if exit_code.signal is not None:
        print("exitsignal=" + str(exit_code.signal))
    print("walltime=" + str(result['walltime']) + "s")
    print("cputime=" + str(result['cputime']) + "s")
    for key in sorted(result.keys()):
        if key.startswith('cputime-'):
            print("{}={:.9f}s".format(key, result[key]))
    print_optional_result('memory')
    print_optional_result('blkio-read', 'B')
    print_optional_result('blkio-write', 'B')
    energy = intel_cpu_energy.format_energy_results(result.get('cpuenergy'))
    for energy_key, energy_value in energy.items():
        print('{}={}J'.format(energy_key, energy_value))
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)
1112004
public static void main(String[] args) throws InterruptedException {
		final ExecutorService executorService = Executors.newFixedThreadPool(1000);
		BenchmarkUtils.run(1, 2,
			// low contention - single thread
			new BenchmarkUtils.Task("1") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 1, executorService).execute();
				}
			},
			// medium contention
			new BenchmarkUtils.Task("CPU") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, AVAILABLE_PROCESSORS, executorService).execute();
				}
			},
			// High contention
			new BenchmarkUtils.Task("400") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 400, executorService).execute();
				}
			}
		);
		executorService.shutdown();

		// we're not using Benchmark results here this time, so we have to extract them on our own
		StopwatchSample sampleLo = SimonManager.getStopwatch("MT-1").sample();
		StopwatchSample sampleCpu = SimonManager.getStopwatch("MT-" + AVAILABLE_PROCESSORS).sample();
		StopwatchSample sampleHi = SimonManager.getStopwatch("MT-400").sample();

		System.out.println("\nsampleLo = " + sampleLo);
		System.out.println("sampleCpu = " + sampleCpu);
		System.out.println("sampleHi = " + sampleHi);

		System.out.println("\nGoogle Chart avg:\n" +
			GoogleChartImageGenerator.barChart("MultithreadedContention", SimonUnit.NANOSECOND,
				sampleLo,
				sampleCpu,
				sampleHi));
		System.out.println("\nGoogle Chart avg/min/max:\n" +
			GoogleChartImageGenerator.barChart("MultithreadedContention", SimonUnit.NANOSECOND, true,
				sampleLo,
				sampleCpu,
				sampleHi));
	}
55229
def main(cls, args, settings=None, userdata=None):  # pylint: disable=too-many-branches,too-many-statements
        
        # The command-line client uses Service Account authentication.
        logger.info('Using Compute Engine credentials from %s', Focus.info(args.conf.name))
        try:
            key = json.loads(args.conf.read())
        except ValueError as msg:
            logger.error('Unable to parse %s: %s', args.conf.name, msg)
            return 1

        # Compute Engine Manager
        try:
            cluster = ComputeEngineManager(key['client_email'], args.conf.name, key['project_id'])
            cluster.connect()
            # Remove read |key| from memory which contains the private key.
            del key
        except ComputeEngineManagerException as msg:
            logger.error(msg)
            return 1

        # Create one or many compute VMs.
        if args.create:
            if args.tags:
                logger.info('Assigning the following tags to the instance: %r', args.tags)

            container_declaration = args.declaration.read()
            try:
                disk = cluster.build_bootdisk(args.image, args.disk_size, args.disk_auto_delete)
                conf = cluster.build_container_vm(container_declaration, disk,
                                                  zone=args.zone,
                                                  tags=args.tags,
                                                  preemptible=args.preemptible)
            except ComputeEngineManagerException as msg:
                logging.error(msg)
                return 1

            logging.debug('VM Configuration: %r', conf)
            try:
                logging.info('Creating %d VM%s of type "%s" ...',
                             args.count, Common.pluralize(args.count), args.size)
                nodes = cluster.create(args.size, args.count, conf, image=args.image)
                for node in nodes:
                    logging.info('Node %s created and %s.', node.name, node.state)
            except ComputeEngineManagerException as msg:
                logging.error(msg)
                return 1

        # Run filters before dealing with any state routine.
        nodes = []
        if any([args.stop, args.start, args.reboot, args.terminate]):
            nodes = cls.list(cls, cluster, args.zone, args.states, args.names, args.tags)

        # Routines for other VM states.
        if args.start:
            try:
                logger.info("Starting %d node%s ...", len(nodes), Common.pluralize(nodes))
                cluster.start(nodes)
            except ComputeEngineManagerException as msg:
                logger.error(msg)
                return 1

        if args.stop:
            try:
                logger.info("Stopping %d node%s ...", len(nodes), Common.pluralize(nodes))
                cluster.stop(nodes)
            except ComputeEngineManagerException as msg:
                logger.error(msg)
                return 1

        if args.reboot:
            try:
                logger.info("Rebooting %d node%s ...", len(nodes), Common.pluralize(nodes))
                cluster.reboot(nodes)
            except ComputeEngineManagerException as msg:
                logger.error(msg)
                return 1

        if args.terminate:
            try:
                logger.info("Terminating %d node%s ...", len(nodes), Common.pluralize(nodes))
                cluster.terminate_ex(nodes, True)
            except ComputeEngineManagerException as msg:
                logger.error(msg)
                return 1

        if args.list:
            try:
                nodes = cls.list(cls, cluster, args.zone, args.states, args.names, args.tags)
                for node in nodes:
                    logging.info('Node: %s is %s; IP: %s (%s); Preemtible: %s',
                                 node.name, node.state,
                                 Kurz.ips(node), Kurz.zone(node), Kurz.is_preemtible(node))
            except ComputeEngineManagerException as msg:
                logger.error(msg)
                return 1

        return 0
89703
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="rockfinder",
        defaultSettingsFile=True
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # CALL FUNCTIONS/OBJECTS

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/rockfinder/rockfinder.yaml"
        cmd = """open %(filepath)s""" % locals()
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        return

    if where and orbfitFlag:
        from rockfinder import orbfit_ephemeris
        eph = orbfit_ephemeris(
            log=log,
            objectId=objectId,
            mjd=mjd,
            obscode=obscode,
            settings=settings,
            verbose=extraFlag
        )
    else:
        from rockfinder import jpl_horizons_ephemeris
        eph = jpl_horizons_ephemeris(
            log=log,
            objectId=objectId,
            mjd=mjd,
            obscode=obscode,
            verbose=extraFlag
        )

    dataSet = list_of_dictionaries(
        log=log,
        listOfDictionaries=eph
    )
    # xfundamentals-render-list-of-dictionaries

    output = dataSet.table(filepath=None)
    if csv:
        output = dataSet.csv(filepath=None)
    elif json:
        output = dataSet.json(filepath=None)
    elif yaml:
        output = dataSet.yaml(filepath=None)
    elif md:
        output = dataSet.markdown(filepath=None)
    elif rst:
        output = dataSet.reST(filepath=None)

    print output

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
891701
def main():
    
    parser = argparse.ArgumentParser(
        description='Performs clustering from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-X", metavar="heap", dest="heap", help="max heap size for jvm, e.g., 512m")
    parser.add_argument("-t", metavar="train", dest="train", required=True, help="training set file")
    parser.add_argument("-T", metavar="test", dest="test", help="test set file")
    parser.add_argument("-d", metavar="outmodel", dest="outmodel", help="model output file name")
    parser.add_argument("-l", metavar="inmodel", dest="inmodel", help="model input file name")
    parser.add_argument("-p", metavar="attributes", dest="attributes", help="attribute range")
    parser.add_argument("-x", metavar="num folds", dest="numfolds", help="number of folds")
    parser.add_argument("-s", metavar="seed", dest="seed", help="seed value for randomization")
    parser.add_argument("-c", metavar="class index", dest="classindex", help="1-based class attribute index")
    parser.add_argument("-g", metavar="graph", dest="graph", help="graph output file (if supported)")
    parser.add_argument("clusterer", help="clusterer classname, e.g., weka.clusterers.SimpleKMeans")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="additional clusterer options")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)
    params = []
    if parsed.train is not None:
        params.extend(["-t", parsed.train])
    if parsed.test is not None:
        params.extend(["-T", parsed.test])
    if parsed.outmodel is not None:
        params.extend(["-d", parsed.outmodel])
    if parsed.inmodel is not None:
        params.extend(["-l", parsed.inmodel])
    if parsed.attributes is not None:
        params.extend(["-p", parsed.attributes])
    if parsed.numfolds is not None:
        params.extend(["-x", parsed.numfolds])
    if parsed.seed is not None:
        params.extend(["-s", parsed.seed])
    if parsed.classindex is not None:
        params.extend(["-c", parsed.classindex])
    if parsed.graph is not None:
        params.extend(["-g", parsed.graph])

    jvm.start(jars, max_heap_size=parsed.heap, packages=True)

    logger.debug("Commandline: " + join_options(sys.argv[1:]))

    try:
        clusterer = Clusterer(classname=parsed.clusterer)
        if len(parsed.option) > 0:
            clusterer.options = parsed.option
        print(ClusterEvaluation.evaluate_clusterer(clusterer, params))
    except Exception as e:
        print(e)
    finally:
        jvm.stop()
1285676
def script(experiment, projects):
    
    benchbuild_c = local[local.path(sys.argv[0])]
    slurm_script = local.cwd / experiment.name + "-" + str(
        CFG['slurm']['script'])

    srun = local["srun"]
    srun_args = []
    if not CFG["slurm"]["multithread"]:
        srun_args.append("--hint=nomultithread")
    if not CFG["slurm"]["turbo"]:
        srun_args.append("--pstate-turbo=off")

    srun = srun[srun_args]
    srun = srun[benchbuild_c["run"]]

    return __save__(slurm_script, srun, experiment, projects)
854189
def cli(patterns, times, json, csv, rst, md, ref, unit, precision, debug):
    ''''''
    if ref:
        ref = JSON.load(ref)

    filenames = []
    reporters = [CliReporter(ref=ref, debug=debug, unit=unit, precision=precision)]
    kwargs = {}
    for pattern in patterns or ['**/*.bench.py']:
        filenames.extend(resolve_pattern(pattern))
    if json:
        reporters.append(JsonReporter(json, precision=precision))
    if csv:
        reporters.append(CsvReporter(csv, precision=precision))
    if rst:
        reporters.append(RstReporter(rst, precision=precision))
    if md:
        reporters.append(MarkdownReporter(md, precision=precision))
    if times:
        kwargs['times'] = times
    runner = BenchmarkRunner(*filenames, reporters=reporters, debug=debug)
    runner.run(**kwargs)
1271507
public static void main(String[] args) {
		// with or without - results on get/start/stop are virtually the same!
		ExampleUtils.fillManagerWithSimons(100000);

		StopwatchSample[] results = BenchmarkUtils.run(2, 5,
			new BenchmarkUtils.Task("empty") {
				@Override
				public void perform() throws Exception {
					//noinspection StatementWithEmptyBody
					for (int i = 0; i < LOOP; i++) {
					}
				}
			},
			new BenchmarkUtils.Task("millis") {
				@Override
				public void perform() throws Exception {
					for (int i = 0; i < LOOP; i++) {
						System.currentTimeMillis();
					}
				}
			},
			new BenchmarkUtils.Task("nanos") {
				@Override
				public void perform() throws Exception {
					for (int i = 0; i < LOOP; i++) {
						System.nanoTime();
					}
				}
			},
			new BenchmarkUtils.Task("assign-ms") {
				@Override
				public void perform() throws Exception {
					for (int i = 0; i < LOOP; i++) {
						long ms = System.currentTimeMillis();
					}
				}
			},
			new BenchmarkUtils.Task("assign-ns") {
				@Override
				public void perform() throws Exception {
					for (int i = 0; i < LOOP; i++) {
						long ns = System.nanoTime();
					}
				}
			},
			new BenchmarkUtils.Task("just-start") {
				@Override
				public void perform() throws Exception {
					Stopwatch simon = SimonManager.getStopwatch(null);
					for (int i = 0; i < LOOP; i++) {
						simon.start();
					}
				}
			},
			new BenchmarkUtils.Task("start-stop") {
				@Override
				public void perform() throws Exception {
					Stopwatch simon = SimonManager.getStopwatch(null);
					for (int i = 0; i < LOOP; i++) {
						simon.start().stop();
					}
				}
			},
			new BenchmarkUtils.Task("get-start-stop") {
				@Override
				public void perform() throws Exception {
					for (int i = 0; i < LOOP; i++) {
						SimonManager.getStopwatch("some.name").start().stop();
					}
				}
			}
		);

		System.out.println("\nGoogle Chart avg:\n" +
			GoogleChartImageGenerator.barChart("10M-loop duration", results));
		System.out.println("\nGoogle Chart avg/max/min:\n" +
			GoogleChartImageGenerator.barChart("10M-loop duration", results));
	}
193274
public static void main(String[] args) {
		EnvironmentInformation.logEnvironmentInfo(LOG, "YARN TaskExecutor runner", args);
		SignalHandler.register(LOG);
		JvmShutdownSafeguard.installAsShutdownHook(LOG);

		run(args);
	}
334821
def main():
    
    parser = argparse.ArgumentParser(
        description='Executes a data generator from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-X", metavar="heap", dest="heap", help="max heap size for jvm, e.g., 512m")
    parser.add_argument("datagenerator", help="data generator classname, e.g., "
                                              + "weka.datagenerators.classifiers.classification.LED24")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="additional data generator options")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)

    jvm.start(jars, max_heap_size=parsed.heap, packages=True)

    logger.debug("Commandline: " + join_options(sys.argv[1:]))

    try:
        generator = DataGenerator(classname=parsed.datagenerator)
        if len(parsed.option) > 0:
            generator.options = parsed.option
        DataGenerator.make_data(generator, parsed.option)
    except Exception as e:
        print(e)
    finally:
        jvm.stop()
472137
public static void main(String[] args) throws InterruptedException {
		ExampleUtils.fillManagerWithSimons(100000);
		final ExecutorService executorService = Executors.newFixedThreadPool(1000);
		StopwatchSample[] results = BenchmarkUtils.run(1, 2,
			new BenchmarkUtils.Task("1") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 1, executorService).execute();
				}
			},
			new BenchmarkUtils.Task("2") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 2, executorService).execute();
				}
			},
			new BenchmarkUtils.Task("3") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 3, executorService).execute();
				}
			},
			new BenchmarkUtils.Task("4") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 4, executorService).execute();
				}
			},
			new BenchmarkUtils.Task("5") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 5, executorService).execute();
				}
			},
			new BenchmarkUtils.Task("100") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 100, executorService).execute();
				}
			}
		);
		executorService.shutdown();

		System.out.println("\nGoogle Chart avg:\n" +
			GoogleChartImageGenerator.barChart("Multithreaded test", results));
	}
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)
414996
def add_basic_executor_options(argument_parser):
    """"""
    argument_parser.add_argument("args", nargs="+", metavar="ARG",
        help='command line to run (prefix with "--" to ensure all arguments are treated correctly)')
    argument_parser.add_argument("--version", action="version", version="%(prog)s " + __version__)

    verbosity = argument_parser.add_mutually_exclusive_group()
    verbosity.add_argument("--debug", action="store_true",
                           help="show debug output")
    verbosity.add_argument("--quiet", action="store_true",
                           help="show only warnings")
965512
def cli(ctx, board, fpga, pack, type, size, project_dir,
        verbose, verbose_yosys, verbose_arachne):
    """"""

    # Run scons
    exit_code = SCons(project_dir).time({
        'board': board,
        'fpga': fpga,
        'size': size,
        'type': type,
        'pack': pack,
        'verbose': {
            'all': verbose,
            'yosys': verbose_yosys,
            'arachne': verbose_arachne
        }
    })
    ctx.exit(exit_code)
973339
def main(argv=None):
    """"""
    parser = argparse.ArgumentParser(description="Parser benchmark")

    parser.add_argument("--debug", default=False, action="store_true", help="Enable debugging")
    parser.add_argument("--repetitions", type=int, default=10, help="Number of repetitions")
    parser.add_argument("--line-count", type=int, default=5000, help="Number of lines to parse")

    args = parser.parse_args(argv)
    run(args)
1196888
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="transientNamer"
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if search or new or cone:
        if ra:
            tns = transientNamer.search(
                log=log,
                ra=ra,
                dec=dec,
                radiusArcsec=arcsecRadius,
                comments=withCommentsFlag
            )
        if name:
            tns = transientNamer.search(
                log=log,
                name=name,
                comments=withCommentsFlag
            )
        if discInLastDays:
            tns = transientNamer.search(
                log=log,
                discInLastDays=discInLastDays,
                comments=withCommentsFlag
            )

        # Recursively create missing directories
        if outputFlag and not os.path.exists(outputFlag):
            os.makedirs(outputFlag)

        if tableNamePrefix:
            sources, phot, spec, files = tns.mysql(
                tableNamePrefix=tableNamePrefix, dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 1
        elif not render or render == "table":
            sources, phot, spec, files = tns.table(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 4
        elif render == "csv":
            sources, phot, spec, files = tns.csv(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 1
        elif render == "json":
            sources, phot, spec, files = tns.json(dirPath=outputFlag)
            numSources = len(sources.split("{")) - 1
        elif render == "yaml":
            sources, phot, spec, files = tns.yaml(dirPath=outputFlag)
            numSources = len(sources.split("\n-"))
        elif render == "markdown":
            sources, phot, spec, files = tns.markdown(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 2

        if numSources == 1:
            print "%(numSources)s transient found" % locals()
        elif numSources > 1:
            print "%(numSources)s transients found" % locals()

        if not outputFlag:
            print "\n# Matched Transients"
            print sources
            print "\n# Transient Photometry"
            print phot
            print "\n# Transient Spectra"
            print spec
            print "\n# Transient Supplementary Files"
            print files
            print "\n# Original TNS Search URL"
            print tns.url
        # CALL FUNCTIONS/OBJECTS

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return