Initializes Profiling via XHProf.
See: https://github.com/piwik/piwik/blob/master/tests/README.xhprof.md
355445
public static function setupProfilerXHProf($mainRun = false, $setupDuringTracking = false)
    {
        if (!$setupDuringTracking
            && SettingsServer::isTrackerApiRequest()
        ) {
            // do not profile Tracker
            return;
        }

        if (self::$isXhprofSetup) {
            return;
        }

        $hasXhprof = function_exists('xhprof_enable');
        $hasTidewaysXhprof = function_exists('tideways_xhprof_enable');

        if (!$hasXhprof && !$hasTidewaysXhprof) {
            $xhProfPath = PIWIK_INCLUDE_PATH . '/vendor/facebook/xhprof/extension/modules/xhprof.so';
            throw new Exception("Cannot find xhprof_enable, make sure to 1) install xhprof: run 'composer install --dev' and build the extension, and 2) add 'extension=$xhProfPath' to your php.ini.");
        }

        $outputDir = ini_get("xhprof.output_dir");
        if (!$outputDir && $hasTidewaysXhprof) {
            $outputDir = sys_get_temp_dir();
        }

        if (empty($outputDir)) {
            throw new Exception("The profiler output dir is not set. Add 'xhprof.output_dir=...' to your php.ini.");
        }
        if (!is_writable($outputDir)) {
            throw new Exception("The profiler output dir '" . ini_get("xhprof.output_dir") . "' should exist and be writable.");
        }

        if (!function_exists('xhprof_error')) {
            function xhprof_error($out)
            {
                echo substr($out, 0, 300) . '...';
            }
        }

        $currentGitBranch = SettingsPiwik::getCurrentGitBranch();
        $profilerNamespace = "piwik";
        if ($currentGitBranch != 'master') {
            $profilerNamespace .= "-" . $currentGitBranch;
        }

        if ($mainRun) {
            self::setProfilingRunIds(array());
        }

        if (function_exists('xhprof_enable')) {
            xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
        } elseif (function_exists('tideways_xhprof_enable')) {
            tideways_xhprof_enable(TIDEWAYS_XHPROF_FLAGS_MEMORY | TIDEWAYS_XHPROF_FLAGS_CPU);
        }

        register_shutdown_function(function () use ($profilerNamespace, $mainRun, $outputDir) {
            if (function_exists('xhprof_disable')) {
                $xhprofData = xhprof_disable();
                $xhprofRuns = new XHProfRuns_Default();
                $runId = $xhprofRuns->save_run($xhprofData, $profilerNamespace);
            } elseif (function_exists('tideways_xhprof_disable')) {
                $xhprofData = tideways_xhprof_disable();
                $runId = uniqid();
                file_put_contents(
                    $outputDir . DIRECTORY_SEPARATOR . $runId . '.' . $profilerNamespace . '.xhprof',
                    serialize($xhprofData)
                );
            }

            if (empty($runId)) {
                die('could not write profiler run');
            }

            $runs = Profiler::getProfilingRunIds();
            array_unshift($runs, $runId);

            if ($mainRun) {
                Profiler::aggregateXhprofRuns($runs, $profilerNamespace, $saveTo = $runId);

                $baseUrlStored = SettingsPiwik::getPiwikUrl();

                $out = "\n\n";
                $baseUrl = "http://" . @$_SERVER['HTTP_HOST'] . "/" . @$_SERVER['REQUEST_URI'];
                if (strlen($baseUrlStored) > strlen($baseUrl)) {
                    $baseUrl = $baseUrlStored;
                }
                $baseUrl = $baseUrlStored . "vendor/facebook/xhprof/xhprof_html/?source=$profilerNamespace&run=$runId";

                $out .= "Profiler report is available at:\n";
                $out .= "<a href='$baseUrl'>$baseUrl</a>";
                $out .= "\n\n";

                if (Development::isEnabled()) {
                    $out .= "WARNING: Development mode is enabled. Many runtime optimizations are not applied in development mode. ";
                    $out .= "Unless you intend to profile Matomo in development mode, your profile may not be accurate.";
                    $out .= "\n\n";
                }

                echo $out;
            } else {
                Profiler::setProfilingRunIds($runs);
            }
        });

        self::$isXhprofSetup = true;
    }
1153858
def mapper_init(self):
        
        self.counties = CachedCountyLookup(precision=GEOHASH_PRECISION)
        self.extractor = WordExtractor()
300516
def profiler():
    ''''''
    import cProfile
    import pstats
    pr = cProfile.Profile()
    pr.enable()
    yield
    pr.disable()
    ps = pstats.Stats(pr).sort_stats('tottime')
    ps.print_stats()
793289
def profile(curr_step, start_step, end_step, profile_name='profile.json',
            early_exit=True):
    """"""
    if curr_step == start_step:
        mx.nd.waitall()
        mx.profiler.set_config(profile_memory=False, profile_symbolic=True,
                               profile_imperative=True, filename=profile_name,
                               aggregate_stats=True)
        mx.profiler.set_state('run')
    elif curr_step == end_step:
        mx.nd.waitall()
        mx.profiler.set_state('stop')
        logging.info(mx.profiler.dumps())
        mx.profiler.dump()
        if early_exit:
            exit()
1144464
def initialize(self, all_options):
    
    if self.run_info:
      raise AssertionError('RunTracker.initialize must not be called multiple times.')

    # Initialize the run.

    # Select a globally unique ID for the run, that sorts by time.
    millis = int((self._run_timestamp * 1000) % 1000)
    # run_uuid is used as a part of run_id and also as a trace_id for Zipkin tracing
    run_uuid = uuid.uuid4().hex
    run_id = 'pants_run_{}_{}_{}'.format(
      time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime(self._run_timestamp)),
      millis,
      run_uuid
    )

    info_dir = os.path.join(self.get_options().pants_workdir, self.options_scope)
    self.run_info_dir = os.path.join(info_dir, run_id)
    self.run_info = RunInfo(os.path.join(self.run_info_dir, 'info'))
    self.run_info.add_basic_info(run_id, self._run_timestamp)
    self.run_info.add_info('cmd_line', self._cmd_line)

    # Create a 'latest' symlink, after we add_infos, so we're guaranteed that the file exists.
    link_to_latest = os.path.join(os.path.dirname(self.run_info_dir), 'latest')

    relative_symlink(self.run_info_dir, link_to_latest)

    # Time spent in a workunit, including its children.
    self.cumulative_timings = AggregatedTimings(os.path.join(self.run_info_dir,
                                                             'cumulative_timings'))

    # Time spent in a workunit, not including its children.
    self.self_timings = AggregatedTimings(os.path.join(self.run_info_dir, 'self_timings'))

    # Hit/miss stats for the artifact cache.
    self.artifact_cache_stats = ArtifactCacheStats(os.path.join(self.run_info_dir,
                                                                'artifact_cache_stats'))

    # Daemon stats.
    self.pantsd_stats = PantsDaemonStats()

    self._all_options = all_options

    return (run_id, run_uuid)
1319365
def init(opts):
    '''
    
    '''
    opts['multiprocessing'] = False
    log.debug('Opening connection to junos')

    args = {"host": opts['proxy']['host']}
    optional_args = ['user',
                     'username',
                     'password',
                     'passwd',
                     'port',
                     'gather_facts',
                     'mode',
                     'baud',
                     'attempts',
                     'auto_probe',
                     'ssh_private_key_file',
                     'ssh_config',
                     'normalize'
                     ]

    if 'username' in opts['proxy'].keys():
        opts['proxy']['user'] = opts['proxy'].pop('username')
    proxy_keys = opts['proxy'].keys()
    for arg in optional_args:
        if arg in proxy_keys:
            args[arg] = opts['proxy'][arg]

    thisproxy['conn'] = jnpr.junos.Device(**args)
    try:
        thisproxy['conn'].open()
    except (ProbeError, ConnectAuthError, ConnectRefusedError, ConnectTimeoutError,
            ConnectError) as ex:
        log.error("{} : not able to initiate connection to the device".format(str(ex)))
        thisproxy['initialized'] = False
        return

    if 'timeout' in proxy_keys:
        timeout = int(opts['proxy']['timeout'])
        try:
            thisproxy['conn'].timeout = timeout
        except Exception as ex:
            log.error('Not able to set timeout due to: %s', str(ex))
        else:
            log.debug('RPC timeout set to %d seconds', timeout)

    try:
        thisproxy['conn'].bind(cu=jnpr.junos.utils.config.Config)
    except Exception as ex:
        log.error('Bind failed with Config class due to: {}'.format(str(ex)))

    try:
        thisproxy['conn'].bind(sw=jnpr.junos.utils.sw.SW)
    except Exception as ex:
        log.error('Bind failed with SW class due to: {}'.format(str(ex)))
    thisproxy['initialized'] = True
781954
def _initialize_integrity_checkers(self, options):
        # type: (Descriptor, blobxfer.models.options.Download) -> None
        
        if self._ase.is_encrypted:
            # ensure symmetric key exists
            if blobxfer.util.is_none_or_empty(
                    self._ase.encryption_metadata.symmetric_key):
                raise RuntimeError(
                    'symmetric key is invalid: provide RSA private key '
                    'or metadata corrupt')
            self.hmac = self._ase.encryption_metadata.initialize_hmac()
        if (self.hmac is None and options.check_file_md5 and
                blobxfer.util.is_not_empty(self._ase.md5)):
            self.md5 = blobxfer.util.new_md5_hasher()
1089259
function profile1() {
  var start, end;
  var totalTimes = [];
  var totalMS = 0;
  var loopIterations = P1_ITER;
  var idx, results;
  
  createDatabase(false);
  
  for(idx=0; idx<P1_ITER; idx++) {
    start = process.hrtime();

    results = coll.chain().simplesort("b").data();

    end = process.hrtime(start);
    totalTimes.push(end);
  }
  
  for (var idx = 0; idx < totalTimes.length; idx++) {
    totalMS += totalTimes[idx][0] * 1e3 + totalTimes[idx][1] / 1e6;
  }

  totalMS = totalMS.toFixed(2);
  var rate = loopIterations * 1000 / totalMS;
  rate = rate.toFixed(2);
  console.log("'a' unfiltered, 'b' unindexed : " + totalMS + "ms (" + rate + " ops/s) " + loopIterations + " iterations");
}
632634
protected function onProfilerInit(ProfilerInterface $profiler) {
		if ($profiler instanceof ProfilerExtendedInterface) {
			$name = get_class($this->getBackend());
			$pos  = strrpos($name, '\\');
			
			$profiler->setName($pos === false ? $name : substr($name, $pos + 1));
			$profiler->setIcon('lightning');
			
			$profiler->addAdditionalInfo(
				'__TOPOLOGY__',
				$this->getTopology()
			);
		}
	}
57629
def _init():
    
    global config, _data_path, _allowed_config_keys

    app_dir = _get_vispy_app_dir()
    if app_dir is not None:
        _data_path = op.join(app_dir, 'data')
        _test_data_path = op.join(app_dir, 'test_data')
    else:
        _data_path = _test_data_path = None

    # All allowed config keys and the types they may have
    _allowed_config_keys = {
        'data_path': string_types,
        'default_backend': string_types,
        'gl_backend': string_types,
        'gl_debug': (bool,),
        'glir_file': string_types+file_types,
        'include_path': list,
        'logging_level': string_types,
        'qt_lib': string_types,
        'dpi': (int, type(None)),
        'profile': string_types + (type(None),),
        'audit_tests': (bool,),
        'test_data_path': string_types + (type(None),),
    }

    # Default values for all config options
    default_config_options = {
        'data_path': _data_path,
        'default_backend': '',
        'gl_backend': 'gl2',
        'gl_debug': False,
        'glir_file': '',
        'include_path': [],
        'logging_level': 'info',
        'qt_lib': 'any',
        'dpi': None,
        'profile': None,
        'audit_tests': False,
        'test_data_path': _test_data_path,
    }

    config = Config(**default_config_options)

    try:
        config.update(**_load_config())
    except Exception as err:
        raise Exception('Error while reading vispy config file "%s":\n  %s' %
                        (_get_config_fname(), err.message))
    set_log_level(config['logging_level'])

    _parse_command_line_arguments()
674965
public static function init() :void {

		// marker
		Profiler::setMarker('Bundles.init', 'framework');

		// if cache is enabled and in prod load the cache, else parse bundles
		Config::isProd() && Cache::has('Includes') ? self::loadCachedDependencies() : self::loadDependencies();
		
		// now that we have the list of config files, pass them to the config class
		Config::includeBundlesConfigs(self::$_configs);

		// now that we have the list of route files, pass them to the router class
		Router::includeBundlesRoutes(self::$_routes);

		// marker
		Profiler::releaseMarker('Bundles.init');

	}
586513
private function initialize()
    {
        $this->extension = 'module';
        $this->extensions = [
            'module' => [],
            'theme' => [],
            'profile' => [],
        ];
        $this->filters = [
            'showInstalled' => false,
            'showUninstalled' => false,
            'showCore' => false,
            'showNoCore' => false
        ];
    }
1185535
def profile_func(filename=None):
    '''
    
    '''
    def proffunc(fun):
        def profiled_func(*args, **kwargs):
            logging.info('Profiling function %s', fun.__name__)
            try:
                profiler = cProfile.Profile()
                retval = profiler.runcall(fun, *args, **kwargs)
                profiler.dump_stats((filename or '{0}_func.profile'
                                     .format(fun.__name__)))
            except IOError:
                logging.exception('Could not open profile file %s', filename)

            return retval
        return profiled_func
    return proffunc
1350502
public function registerProfiler()
	{
		$sessionHash = static::SESSION_HASH;

		$this->app['profiler'] = $this->app->share(function($app) use ($sessionHash)
		{
			$startTime = null;
			$enabled = false;

			// Let's use the Laravel start time if it is defined.
			if(defined('LARAVEL_START'))
			{
				$startTime = LARAVEL_START;
			}

			// Check the session to see if the profiler has been manually enabled
			// or disabled through the session. Note that the session completely overrides
			// the configuration.
			if($app['session']->has($sessionHash))
			{
				$enabled = $app['session']->get($sessionHash);
			}
			
			else
			{
				// The session contains no information as to wether the profiler is enabled
				// or not. Let's check the configurations now. 
				$enabled = $app['config']->get('profiler::enabled', null);

				// If the config is set to null (or doesn't exist), we will fallback to the application's
				// debug setting.
				if(is_null($enabled))
				{
					$enabled = $app['config']->get('app.debug');
				}
			}

			return new Profiler(new Logger, $startTime, $enabled);
		});
	}
184071
def Initialize(api_key, api_secret, api_host="localhost", api_port=443, api_ssl=True, asyncblock=False, timeout=10, req_method="get"):
    
    config = Config()

    if api_ssl:
        proto = "https"
    else:
        proto = "http"
    api_url = "%s://%s:%s/client/api" % (proto, api_host, api_port)
    if os.access(os.path.expanduser("~") , os.W_OK):
        d = os.path.expanduser("~")
    else:
        d = tempfile.gettempdir()
    cache_file = os.getenv('MOLNCTRL_CACHE') or '.molnctrl_cache'
    if os.path.exists(os.path.join(d, cache_file)):
        apicache = pickle.load(open( os.path.join(d, cache_file), "rb" ))
    else:
        method = {'description': u'lists all available apis on the server, provided by the Api Discovery plugin',
            'isasync': False,
            'name': u'listApis',
            'params': [{'description': u'API name',
            'length': 255,
            'name': u'name',
            'related': [],
            'required': False,
            'type': u'string'}],
            'related': [],
            'requiredparams': []}
        _create_api_method(CSApi, "list_apis", method)
        c = CSApi(api_url, api_key, api_secret, asyncblock)
        apicache = cachemaker.monkeycache(c.list_apis())
        pickle.dump(apicache, open(os.path.join(d, cache_file), "wb"))

    for verb, methods in six.iteritems(apicache):
        if isinstance(methods, dict):
            for method in six.iterkeys(methods):
                _create_api_method(CSApi, "%s_%s" % (verb, method), methods[method])
    return CSApi(api_url, api_key, api_secret, asyncblock, timeout, req_method)
394069
def profiler(self):
        
        # Initialise variables
        profiledata = defaultdict(make_dict)
        profileset = set()
        genedict = {}
        # Find all the unique profiles to use with a set
        for sample in self.metadata.samples:
            if sample[self.analysistype].profile != 'NA':
                profileset.add(sample[self.analysistype].profile[0])
        # Extract the profiles for each set
        for sequenceprofile in profileset:
            # Clear the list of genes
            genelist = []
            for sample in self.metadata.samples:
                if sequenceprofile == sample[self.analysistype].profile[0]:
                    genelist = [os.path.split(x)[1].split('.')[0] for x in sample[self.analysistype].alleles]
            try:
                # Open the sequence profile file as a dictionary
                profile = DictReader(open(sequenceprofile))
            # Revert to standard comma separated values
            except KeyError:
                # Open the sequence profile file as a dictionary
                profile = DictReader(open(sequenceprofile))
            # Iterate through the rows
            for row in profile:
                # Iterate through the genes
                for gene in genelist:
                    # Add the sequence profile, and type, the gene name and the allele number to the dictionary
                    try:
                        profiledata[sequenceprofile][row['ST']][gene] = row[gene]
                    except KeyError:
                        pass
            # Add the gene list to a dictionary
            genedict[sequenceprofile] = sorted(genelist)
            # Add the profile data, and gene list to each sample
            for sample in self.metadata.samples:
                if sample.general.bestassemblyfile != 'NA':
                    if sequenceprofile == sample[self.analysistype].profile[0]:
                        # Populate the metadata with the profile data
                        sample[self.analysistype].profiledata = profiledata[sample[self.analysistype].profile[0]]
                        # Add the allele directory to a list of directories used in this analysis
                        self.allelefolders.add(sample[self.analysistype].alleledir)
                        dotter()
164841
def profile(script, argv, profiler_factory,
            pickle_protocol, dump_filename, mono):
    """"""
    filename, code, globals_ = script
    sys.argv[:] = [filename] + list(argv)
    __profile__(filename, code, globals_, profiler_factory,
                pickle_protocol=pickle_protocol, dump_filename=dump_filename,
                mono=mono)