當前位置: 首頁>>代碼示例>>Python>>正文


Python cProfile.runctx方法代碼示例

本文整理匯總了Python中cProfile.runctx方法的典型用法代碼示例。如果您正苦於以下問題:Python cProfile.runctx方法的具體用法?Python cProfile.runctx怎麽用?Python cProfile.runctx使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cProfile的用法示例。


在下文中一共展示了cProfile.runctx方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: run_prof

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def run_prof(cls, num, total_worker_count, worker_num, response_queue, new_job_queue, cookie_lock, nosig=True):

		logSetup.resetLoggingLocks()
		common.process.name_process("raw fetcher processing worker w-profiling")

		pid = os.getpid()
		try:
			cProfile.runctx('cls.run(num, response_queue, new_job_queue, cookie_lock, nosig)', globals(), locals(), 'prof%d.prof' % pid)
		except Exception as e:
			print("Wat?")
			print("Wat?")
			print("Wat?")
			print("Wat?")
			print("Wat?")
			print("Wat?")
			print("Wat?")
			traceback.print_exc()
			raise e 
開發者ID:fake-name,項目名稱:ReadableWebProxy,代碼行數:20,代碼來源:RawRunner.py

示例2: run_prof

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def run_prof(cls, num, total_worker_count, worker_num, response_queue, new_job_queue, cookie_lock, nosig=True):

		logSetup.resetLoggingLocks()
		common.process.name_process("proc fetcher processing worker w-profiling")

		pid = os.getpid()
		try:
			cProfile.runctx('cls.run(num, response_queue, new_job_queue, cookie_lock, nosig)', globals(), locals(), 'prof%d.prof' % pid)
		except Exception as e:
			print("Wat?")
			print("Wat?")
			print("Wat?")
			print("Wat?")
			print("Wat?")
			print("Wat?")
			print("Wat?")
			traceback.print_exc()
			raise e 
開發者ID:fake-name,項目名稱:ReadableWebProxy,代碼行數:20,代碼來源:Runner.py

示例3: profile

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def profile(model_specification, results_directory, process):
    """Run a simulation based on the provided MODEL_SPECIFICATION and profile
    the run.
    """
    model_specification = Path(model_specification)
    results_directory = Path(results_directory)

    out_stats_file = results_directory / f'{model_specification.name}'.replace('yaml', 'stats')
    command = f'run_simulation("{model_specification}")'
    cProfile.runctx(command, globals=globals(), locals=locals(), filename=out_stats_file)

    if process:
        out_txt_file = results_directory / (out_stats_file.name + '.txt')
        with out_txt_file.open('w') as f:
            p = pstats.Stats(str(out_stats_file), stream=f)
            p.sort_stats('cumulative')
            p.print_stats() 
開發者ID:ihmeuw,項目名稱:vivarium,代碼行數:19,代碼來源:cli.py

示例4: _run

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def _run(self):
        """Private helper that wraps .run() and sets various exit flags."""
        try:
            if do_profiling.value:
                import cProfile
                import tempfile
                (fd, filename) = tempfile.mkstemp(suffix=".prof")
                print("Profile info: {}".format(filename))
                cProfile.runctx("self.run()", globals(), locals(), filename=filename)
            else:
                self.run()
            self._flags[2] = True
        except Exception as e:
            import traceback
            traceback.print_exc()
        self._flags[1] = True 
開發者ID:CozySynthesizer,項目名稱:cozy,代碼行數:18,代碼來源:jobs.py

示例5: runctx

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def runctx(cmdstr, globals={}, locals={}, outpath=None, executable=None):
    tmp = tempfile.mktemp()
    target = tmp

    # profile to a file
    if outpath is not None:
        target = fileutil.FilePath(outpath).ensureExt('callgrind')

        # ensure out folder exists
        target.parent().ensureExists()

    # profile into out file
    cProfile.runctx(cmdstr, globals, locals, filename=tmp)
    pyprof2calltree.convert(pstats.Stats(tmp), target)

    # open
    if executable is not None:
        subprocess.Popen([executable, target])

    # clean up & return result
    if tmp != target:
        os.unlink(tmp)
    return target 
開發者ID:trevorvanhoof,項目名稱:sqrmelon,代碼行數:25,代碼來源:profileutil.py

示例6: train_with_profiling

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def train_with_profiling(opts, dirs):

    import cProfile, pstats, StringIO
    cProfile.runctx('train(opts, dirs)', \
                    {'train': train, 'opts': opts, 'dirs': dirs}, 
                    {}, 'mainstats')

    # create a stream for the profiler to write to
    profiling_output = StringIO.StringIO()
    p = pstats.Stats('mainstats', stream=profiling_output)

    # print stats to that stream
    # here we just report the top 30 functions, sorted by total amount of time spent in each
    p.strip_dirs().sort_stats('cumulative').print_stats(30)

    # print the result to the log
    print('---Profiling result follows---\n%s' %  profiling_output.getvalue() )
    profiling_output.close()
    print('---End of profiling result---') 
開發者ID:CSTR-Edinburgh,項目名稱:Ossian,代碼行數:21,代碼來源:train.py

示例7: set_layer_entity

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def set_layer_entity(self):
        """
        Sets the entity property using the layer table.
        """
        self.layer_table = self.get_layer_source(
            self.iface.activeLayer()
        )
        if self.layer_table == '':
            return

        if self.layer_table in spatial_tables() and \
                        self.layer_table not in pg_views():
            self.entity = self.current_profile.entity_by_name(self.layer_table)
    #
    # def activate_feature_details(self, button_clicked=True):
    #     if cProfile is None:
    #         return
    #     cProfile.runctx('self._activate_feature_details(button_clicked)', globals(), locals()) 
開發者ID:gltn,項目名稱:stdm,代碼行數:20,代碼來源:feature_details.py

示例8: render

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def render(artifact, md, opts):
    start = begin = time.time()
    print("%4s %20s %10s %s" % ('', 'Conversion Time (s)', 'Text Size', 'Post._id'))
    for i, p in enumerate(artifact.discussion_thread.posts):
        text = DUMMYTEXT or p.text
        if opts.n and i + 1 not in opts.n:
            print('Skipping post %s' % str(i + 1))
            continue
        if opts.profile:
            print('Profiling post %s' % str(i + 1))
            cProfile.runctx('output = md.convert(text)', globals(), locals())
        else:
            output = md.convert(text)
        elapsed = time.time() - start
        print("%4s %1.18f %10s %s" % (i + 1, elapsed, len(text), p._id))
        if opts.output:
            print('Input:', text[:min(300, len(text))])
            print('Output:', output[:min(MAX_OUTPUT, len(output))])
        start = time.time()
    print("Total time:", start - begin)
    return output 
開發者ID:apache,項目名稱:allura,代碼行數:23,代碼來源:md_perf.py

示例9: balfreq_profiling

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def balfreq_profiling(self):
        """
        Generate profiling report for balfreq function and saves it into ``self.prof_out.``
        The function also returns a ``pstats.Stats`` object.

        To read the report:
            .. code-block:: python

                import pstats
                p=pstats.Stats(self.prof_out).sort_stats('cumtime')
                p.print_stats(20)
        """
        import pstats
        import cProfile
        def wrap():
            DictBalFreq = {'frequency': 0.5, 'check_stability': False}
            self.balfreq(DictBalFreq)
        cProfile.runctx('wrap()', globals(), locals(), filename=self.prof_out)

        cProfile.runctx('wrap()', globals(), locals(), filename=self.prof_out)

        return pstats.Stats(self.prof_out).sort_stats('cumtime') 
開發者ID:ImperialCollegeLondon,項目名稱:sharpy,代碼行數:24,代碼來源:linuvlm.py

示例10: profile

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def profile(num_elements=100000, parser="lxml"):

    filehandle = tempfile.NamedTemporaryFile()
    filename = filehandle.name

    data = rdoc(num_elements)
    vars = dict(bs4=bs4, data=data, parser=parser)
    cProfile.runctx('bs4.BeautifulSoup(data, parser)' , vars, vars, filename)

    stats = pstats.Stats(filename)
    # stats.strip_dirs()
    stats.sort_stats("cumulative")
    stats.print_stats('_html5lib|bs4', 50) 
開發者ID:MarcelloLins,項目名稱:ServerlessCrawler-VancouverRealState,代碼行數:15,代碼來源:diagnose.py

示例11: train_loop_with_profile

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def train_loop_with_profile(process_idx, counter, make_env, max_score, args,
                            agent, env, start_time, outdir):
    import cProfile
    cmd = 'train_loop(process_idx, counter, make_env, max_score, args, ' \
        'agent, env, start_time)'
    cProfile.runctx(cmd, globals(), locals(),
                    'profile-{}.out'.format(os.getpid())) 
開發者ID:muupan,項目名稱:async-rl,代碼行數:9,代碼來源:run_a3c.py

示例12: train_loop_with_profile

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def train_loop_with_profile(process_idx, counter, max_score, args, agent, env,
                            start_time):
    import cProfile
    cmd = 'train_loop(process_idx, counter, max_score, args, agent, env, ' \
        'start_time)'
    cProfile.runctx(cmd, globals(), locals(),
                    'profile-{}.out'.format(os.getpid())) 
開發者ID:muupan,項目名稱:async-rl,代碼行數:9,代碼來源:a3c_ale.py

示例13: perform_profiling

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def perform_profiling(mod_name, repeat=1, seed=0, filename=fn_template, **kwargs):
    """Run profiling of the `benchmark` function in the given module.

    Parameters
    ----------
    mod_name : str
        The name of a module containing the benchmark.
        Must define the functions ``data = setup_benchmark(size, **kwargs)``,
        which is followed by multiple ``benchmark(data)``, which should be benchmarked.
    repeat : int
        Repeat the `benchmark` function to be profiled that many times.
    seed : int
        Seed of the random number generator with this number to enhance reproducability
    filename : str
        Template for the filename.
    **kwargs :
        Further arguments given to the `setup_benchmark` function.
        Note: is formated to a string with ``repr(kwargs)``. Don't use too complicated arguements!
    """
    kwargs['mod_name'] = mod_name
    filename = filename.format(mod_q_str='_'.join([str(q) for q in kwargs['mod_q']]), **kwargs)
    np.random.seed(seed)
    setup_code = "import {mod_name!s}\ndata = {mod_name!s}.setup_benchmark(**{kwargs!r})"
    setup_code = setup_code.format(mod_name=mod_name, kwargs=kwargs)
    namespace = {}
    exec(setup_code, namespace, namespace)
    timing_code = "{mod_name}.benchmark(data)".format(mod_name=mod_name)
    if repeat > 1:
        timing_code = "for _ in range({repeat:d}): ".format(repeat=repeat) + timing_code
    if sys.version_info > (3, 3):
        prof = cProfile.Profile(time.perf_counter)
    else:
        prof = cProfile.Profile()
    prof.runctx(timing_code, namespace, namespace)
    prof.dump_stats(filename)

    #  cProfile.runctx(timing_code, namespace, namespace, filename)
    print("saved profiling to", filename)
    return filename 
開發者ID:tenpy,項目名稱:tenpy,代碼行數:41,代碼來源:profiling.py

示例14: scale

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def scale(image, function, profile):
    if profile:
        print("Scaling using {}()...".format(function))
        cProfile.runctx("{}(image.pixels, image.width, "
                "image.height, 0.5)".format(function), globals(), locals()) 
開發者ID:lovexiaov,項目名稱:python-in-practice,代碼行數:7,代碼來源:benchmark_Scale.py

示例15: command

# 需要導入模塊: import cProfile [as 別名]
# 或者: from cProfile import runctx [as 別名]
def command(self):
        self._load_config_into_test_app()

        import paste.fixture
        import cProfile
        import re

        url = self.args[0]
        if self.args[1:]:
            user = self.args[1]
        else:
            user = 'visitor'

        def profile_url(url):
            try:
                res = self.app.get(url, status=[200],
                                   extra_environ={'REMOTE_USER': user})
            except paste.fixture.AppError:
                print 'App error: ', url.strip()
            except KeyboardInterrupt:
                raise
            except:
                import traceback
                traceback.print_exc()
                print 'Unknown error: ', url.strip()

        output_filename = 'ckan%s.profile' % re.sub('[/?]', '.', url.replace('/', '.'))
        profile_command = "profile_url('%s')" % url
        cProfile.runctx(profile_command, globals(), locals(), filename=output_filename)
        import pstats
        stats = pstats.Stats(output_filename)
        stats.sort_stats('cumulative')
        stats.print_stats(0.1)  # show only top 10% of lines
        print 'Only top 10% of lines shown'
        print 'Written profile to: %s' % output_filename 
開發者ID:italia,項目名稱:daf-recipes,代碼行數:37,代碼來源:cli.py


注:本文中的cProfile.runctx方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。