Profile a Python script.
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)
230701
def profile(func, stream=None):
    
    def wrapper(*args, **kwargs):
        prof = LineProfiler()
        val = prof(func)(*args, **kwargs)
        show_results(prof, stream=stream)
        return val
    return wrapper
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()
590284
def maybe_profiled(profile_path):
  
  if not profile_path:
    yield
    return

  import cProfile
  profiler = cProfile.Profile()
  try:
    profiler.enable()
    yield
  finally:
    profiler.disable()
    profiler.dump_stats(profile_path)
    view_cmd = green('gprof2dot -f pstats {path} | dot -Tpng -o {path}.png && open {path}.png'
                     .format(path=profile_path))
    logging.getLogger().info(
      'Dumped profile data to: {}\nUse e.g. {} to render and view.'.format(profile_path, view_cmd)
    )
582221
def analyze_profile(self):
        """"""
        profile_parser = ProfileParser()
        databases = self._get_requested_databases()
        connection = pymongo.MongoClient(self._db_uri,
                                         document_class=OrderedDict,
                                         read_preference=pymongo.ReadPreference.PRIMARY_PREFERRED)

        if databases == []:
            try:
                databases = connection.database_names()
            except:
                message = "Error: Could not list databases on server. Please " \
                          +         "check the auth components of your URI or provide " \
                          +         "a namespace filter with -n.\n"
                sys.stderr.write(message)
                databases = []

            for ignore_db in IGNORE_DBS:
                if ignore_db in databases:
                    databases.remove(ignore_db)

        for database in databases:

            db = connection[database]

            profile_entries = db['system.profile'].find()

            for profile_entry in profile_entries:
                self._process_query(profile_entry,
                                    profile_parser)

        self._output_aggregated_report(sys.stdout)

        return 0
728897
def profiling():
  
  import cProfile
  n = 10000
  data = np.cumsum(np.random.random(n) - 0.5)
  cProfile.runctx('lyap_e(data)', {'lyap_e': nolds.lyap_e}, {'data': data})
1369337
def profiled_thread(func):
    """'"""

    def wrapper(*args, **kwargs):
        profile = Profile()
        profile.enable()
        try:
            func(*args, **kwargs)
        finally:
            profile.disable()
        try:
            thread = current_thread()
            profile.dump_stats('profile_%s.%s.%s.log' % (getpid(), thread.name, thread.ident))
        except:
            logger.exception('Failed to dump stats')

    return wrapper
508797
def _tail_profile(self, db, interval):
        """"""
        latest_doc = None
        while latest_doc is None:
            time.sleep(interval)
            latest_doc = db['system.profile'].find_one()

        current_time = latest_doc['ts']

        while True:
            time.sleep(interval)
            cursor = db['system.profile'].find({'ts': {'$gte': current_time}}).sort('ts', pymongo.ASCENDING)
            for doc in cursor:
                current_time = doc['ts']
                yield doc
86010
function(editor, syntax, profile) {
			var args = utils.toArray(arguments);
			
			// normalize incoming arguments
			var info = editorUtils.outputInfo(editor, syntax, profile);
			args[1] = info.syntax;
			args[2] = info.profile;
			
			return handlers.exec(false, args);
		}
199153
def process_view(self, request, view_func, view_args, view_kwargs):
        """"""
        profiler = getattr(request, 'profiler', None)
        if profiler:
            # Make sure profiler variables don't get passed into view_func
            original_get = request.GET
            request.GET = original_get.copy()
            request.GET.pop('profile', None)
            request.GET.pop('show_queries', None)
            request.GET.pop('show_stats', None)
            try:
                return profiler.runcall(
                    view_func, request, *view_args, **view_kwargs
                )
            finally:
                request.GET = original_get
428948
def analyze(self, scratch, **kwargs):
        """"""
        results = Counter()
        for script in self.iter_scripts(scratch):
            gen = self.iter_blocks(script.blocks)
            name = 'start'
            level = None
            while name != '':
                if name in self.ANIMATION:
                    gen, count = self._check_animation(name, level, gen)
                    results.update(count)
                name, level, _ = next(gen, ('', 0, ''))
        return {'animation': results}
1139313
def handler_profiler(filename=None):
    
    if filename == None:
        f = sys.stdout
    else:
        f = open(filename, 'w')
    def _callfunc(handle):
        @wraps(handle)
        def func(self, topic, msg):
            t0 = time.time()
            handle(self, topic, msg)
            t1 = time.time()
            print(f'{self.name}-handle运行时间:{t1 - t0}s', file=f)

        return func
    return _callfunc
1053314
def analyze(self, filename):
        """"""
        if self.dockwidget and not self.ismaximized:
            self.dockwidget.setVisible(True)
            self.dockwidget.setFocus()
            self.dockwidget.raise_()
        pythonpath = self.main.get_spyder_pythonpath()
        runconf = get_run_configuration(filename)
        wdir, args = None, []
        if runconf is not None:
            if runconf.wdir_enabled:
                wdir = runconf.wdir
            if runconf.args_enabled:
                args = runconf.args
        self.profiler.analyze(filename, wdir=wdir, args=args,
                              pythonpath=pythonpath)
1266642
def read_profiles(profiles_dir=None):
    """"""
    if profiles_dir is None:
        profiles_dir = PROFILES_DIR

    raw_profiles = read_profile(profiles_dir)

    if raw_profiles is None:
        profiles = {}
    else:
        profiles = {k: v for (k, v) in raw_profiles.items() if k != 'config'}

    return profiles
1375004
def profile(fun, *args, **kwargs):
    
    timer_name = kwargs.pop("prof_name", None)

    if not timer_name:
        module = inspect.getmodule(fun)
        c = [module.__name__]
        parentclass = labtypes.get_class_that_defined_method(fun)
        if parentclass:
            c.append(parentclass.__name__)
        c.append(fun.__name__)
        timer_name = ".".join(c)

    start(timer_name)
    ret = fun(*args, **kwargs)
    stop(timer_name)
    return ret
142000
def profiler(self):
        """"""
        # Initialise variables
        profiledata = defaultdict(make_dict)
        profileset = set()
        # supplementalset = ''
        genedict = {}
        # Find all the unique profiles to use with a set
        for sample in self.metadata:
            if sample[self.analysistype].profile != 'NA':
                profileset.add(sample[self.analysistype].profile[0])
                # if self.analysistype == 'rmlst':
                #     supplementalset = sample[self.analysistype].supplementalprofile
        # Extract the profiles for each set
        for sequenceprofile in profileset:
            # Clear the list of genes
            genelist = []
            for sample in self.metadata:
                if sequenceprofile == sample[self.analysistype].profile[0]:
                    # genelist = [os.path.split(x)[1].split('.')[0] for x in sample[self.analysistype].alleles]
                    genelist = sample[self.analysistype].allelenames
            try:
                # Open the sequence profile file as a dictionary
                profile = DictReader(open(sequenceprofile), dialect='excel-tab')
            # 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:
                        try:
                            profiledata[sequenceprofile][row['rST']][gene] = row[gene]
                        except KeyError:
                            raise

            # # Load the supplemental profile definitions
            # if self.analysistype == 'rmlst':
            #     supplementalprofile = DictReader(open(supplementalset), dialect='excel-tab')
            #     # Do the same with the supplemental profile
            #     for row in supplementalprofile:
            #         # Iterate through the genes
            #         for gene in genelist:
            #             # Add the sequence profile, and type, the gene name and the allele number to the dictionary
            #             profiledata[sequenceprofile][row['rST']][gene] = row[gene]
            # 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:
                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()
264608
def profile_execution(self, status):
        """"""
        self.selected_profile.data['execution_success'] = status
        if status:
            self.report['results']['executions']['pass'] += 1
        else:
            self.report['results']['executions']['fail'] += 1
            if self.selected_profile.name not in self.report['results']['failed_profiles']:
                self.report['results']['failed_profiles'].append(self.selected_profile.name)