当前位置: 首页>>代码示例>>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;未经允许,请勿转载。