当前位置: 首页>>代码示例>>Python>>正文


Python cProfile.Profile方法代码示例

本文整理汇总了Python中cProfile.Profile方法的典型用法代码示例。如果您正苦于以下问题:Python cProfile.Profile方法的具体用法?Python cProfile.Profile怎么用?Python cProfile.Profile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cProfile的用法示例。


在下文中一共展示了cProfile.Profile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def main():
    print('create y...')
    y = np.random.randint(2, size=N_OBS)
    print('create X...')
    row = np.random.randint(N_OBS, size=N_VALUE)
    col = np.random.randint(N_FEATURE, size=N_VALUE)
    data = np.ones(N_VALUE)
    X = sparse.csr_matrix((data, (row, col)), dtype=np.int8)

    print('train...')
    profiler = cProfile.Profile(subcalls=True, builtins=True, timeunit=0.001,)
    clf = FTRL(interaction=False)
    profiler.enable()
    clf.fit(X, y)
    profiler.disable()
    profiler.print_stats()

    p = clf.predict(X)
    print('AUC: {:.4f}'.format(auc(y, p)))

    assert auc(y, p) > .5 
开发者ID:jeongyoonlee,项目名称:Kaggler,代码行数:23,代码来源:test_ftrl.py

示例2: profile

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def profile(fnc):
    """
    Profiles any function in following class just by adding @profile above function
    """
    import cProfile, pstats, io
    def inner (*args, **kwargs):
        pr = cProfile.Profile()
        pr.enable()
        retval = fnc (*args, **kwargs)
        pr.disable()
        s = io.StringIO()
        sortby = 'cumulative'   #Ordered
        ps = pstats.Stats(pr,stream=s).strip_dirs().sort_stats(sortby)
        n=20                    #reduced the list to be monitored
        ps.print_stats(n)
        #ps.dump_stats("profile.prof")
        print(s.getvalue())
        return retval
    return inner 
开发者ID:pyscf,项目名称:pyscf,代码行数:21,代码来源:gw_iter.py

示例3: __call__

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def __call__(self, *args, **kw):
        """Profile a singe call to the function."""
        self.ncalls += 1
        if self.skip > 0:
            self.skip -= 1
            self.skipped += 1
            return self.fn(*args, **kw)
        if FuncProfile.in_profiler:
            # handle recursive calls
            return self.fn(*args, **kw)
        # You cannot reuse the same profiler for many calls and accumulate
        # stats that way.  :-/
        profiler = self.Profile()
        try:
            FuncProfile.in_profiler = True
            return profiler.runcall(self.fn, *args, **kw)
        finally:
            FuncProfile.in_profiler = False
            self.stats.add(profiler)
            if self.immediate:
                self.print_stats()
                self.reset_stats() 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:24,代码来源:profilehooks.py

示例4: profile

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def profile(filename=None, comm=MPI.COMM_WORLD):
    def prof_decorator(f):
        def wrap_f(*args, **kwargs):
            pr = cProfile.Profile()
            pr.enable()
            result = f(*args, **kwargs)
            pr.disable()

            if filename is None:
                pr.print_stats()
            else:
                filename_r = filename  # + ".{}".format(comm.rank)
                pr.dump_stats(filename_r)

            return result
        return wrap_f
    return prof_decorator 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:19,代码来源:profile.py

示例5: profileit

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def profileit(func):
    """
    Decorator straight up stolen from stackoverflow
    """
    def wrapper(*args, **kwargs):
        datafn = func.__name__ + ".profile" # Name the data file sensibly
        prof = cProfile.Profile()
        prof.enable()
        retval = prof.runcall(func, *args, **kwargs)
        prof.disable()
        stats = pstats.Stats(prof)
        stats.sort_stats('tottime').print_stats(20)
        print()
        print()
        stats.sort_stats('cumtime').print_stats(20)
        return retval

    return wrapper 
开发者ID:vertical-knowledge,项目名称:ripozo,代码行数:20,代码来源:profile.py

示例6: _profile_package

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def _profile_package(self):
        """Runs cProfile on a package."""
        prof = cProfile.Profile()
        prof.enable()
        try:
            runpy.run_path(self._run_object, run_name='__main__')
        except SystemExit:
            pass
        prof.disable()
        prof_stats = pstats.Stats(prof)
        prof_stats.calc_callees()
        return {
            'objectName': self._object_name,
            'callStats': self._transform_stats(prof_stats),
            'totalTime': prof_stats.total_tt,
            'primitiveCalls': prof_stats.prim_calls,
            'totalCalls': prof_stats.total_calls,
            'timestamp': int(time.time())
        } 
开发者ID:nvdv,项目名称:vprof,代码行数:21,代码来源:profiler.py

示例7: _profile_module

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def _profile_module(self):
        """Runs cProfile on a module."""
        prof = cProfile.Profile()
        try:
            with open(self._run_object, 'rb') as srcfile:
                code = compile(srcfile.read(), self._run_object, 'exec')
            prof.runctx(code, self._globs, None)
        except SystemExit:
            pass
        prof_stats = pstats.Stats(prof)
        prof_stats.calc_callees()
        return {
            'objectName': self._object_name,
            'callStats': self._transform_stats(prof_stats),
            'totalTime': prof_stats.total_tt,
            'primitiveCalls': prof_stats.prim_calls,
            'totalCalls': prof_stats.total_calls,
            'timestamp': int(time.time())
        } 
开发者ID:nvdv,项目名称:vprof,代码行数:21,代码来源:profiler.py

示例8: profile_function

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def profile_function(self):
        """Runs cProfile on a function."""
        prof = cProfile.Profile()
        prof.enable()
        result = self._run_object(*self._run_args, **self._run_kwargs)
        prof.disable()
        prof_stats = pstats.Stats(prof)
        prof_stats.calc_callees()
        return {
            'objectName': self._object_name,
            'callStats': self._transform_stats(prof_stats),
            'totalTime': prof_stats.total_tt,
            'primitiveCalls': prof_stats.prim_calls,
            'totalCalls': prof_stats.total_calls,
            'result': result,
            'timestamp': int(time.time())
        } 
开发者ID:nvdv,项目名称:vprof,代码行数:19,代码来源:profiler.py

示例9: do_loop

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def do_loop(self, callbacks: List[Callable]):
        if self.env.arguments.enable_profiler:
            profile = cProfile.Profile()
            profile.enable()

        try:
            self.loop.run_until_complete(self.shutdown_future)
        except KeyboardInterrupt:
            pass
        finally:
            for callback in callbacks:
                if callable(callback):
                    callback()

        if self.env.arguments.enable_profiler:
            profile.disable()
            profile.print_stats("time") 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:19,代码来源:master.py

示例10: main

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def main():
    from quarkchain.cluster.jsonrpc import JSONRPCWebsocketServer

    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    env = parse_args()

    if env.arguments.enable_profiler:
        profile = cProfile.Profile()
        profile.enable()
    slave_server = SlaveServer(env)
    slave_server.start()

    callbacks = []
    if env.slave_config.WEBSOCKET_JSON_RPC_PORT is not None:
        json_rpc_websocket_server = JSONRPCWebsocketServer.start_websocket_server(
            env, slave_server
        )
        callbacks.append(json_rpc_websocket_server.shutdown)

    slave_server.do_loop()
    if env.arguments.enable_profiler:
        profile.disable()
        profile.print_stats("time")

    Logger.info("Slave server is shutdown") 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:27,代码来源:slave.py

示例11: __init__

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def __init__(
        self,
        *,
        prefix: str = PREFIX,
        suffix: str = PROF_SUFFIX,
        dir: Optional[str] = None,
        save_every_n_calls: int = 1,
    ):
        """Create the decorator.

        If `save_every_n_calls` is greater than 1, the profiler will not
        dump data to files on every call to the profiled function.  This speeds
        up the running program but risks incomplete data if the process is
        terminated non-gracefully.

        `dir`, `prefix`, and `suffix` after `tempfile.mkstemp`.
        """
        self.prefix = prefix
        self.suffix = suffix
        self.save_every_n_calls = save_every_n_calls
        self.n_calls = 0
        self._dir: Union[str, pathlib.Path, None] = dir
        self._profiler: Optional[cProfile.Profile] = None
        self._dump_file_path: Optional[str] = None 
开发者ID:edgedb,项目名称:edgedb,代码行数:26,代码来源:profiler.py

示例12: profileMain

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def profileMain(args, config):  # pragma: no cover
    """This is the main function for profiling
    http://code.google.com/appengine/kb/commontasks.html#profiling
    """
    import cProfile
    import pstats

    eyed3.log.debug("driver profileMain")
    prof = cProfile.Profile()
    prof = prof.runctx("main(args)", globals(), locals())

    stream = StringIO()
    stats = pstats.Stats(prof, stream=stream)
    stats.sort_stats("time")  # Or cumulative
    stats.print_stats(100)  # 80 = how many to print

    # The rest is optional.
    stats.print_callees()
    stats.print_callers()
    sys.stderr.write("Profile data:\n%s\n" % stream.getvalue())

    return 0 
开发者ID:nicfit,项目名称:eyeD3,代码行数:24,代码来源:main.py

示例13: run

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def run(self, reactor):
        """
        Run reactor under the standard profiler.
        """
        try:
            import profile
        except ImportError as e:
            self._reportImportError("profile", e)

        p = profile.Profile()
        p.runcall(reactor.run)
        if self.saveStats:
            p.dump_stats(self.profileOutput)
        else:
            tmp, sys.stdout = sys.stdout, open(self.profileOutput, 'a')
            try:
                p.print_stats()
            finally:
                sys.stdout, tmp = tmp, sys.stdout
                tmp.close() 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:22,代码来源:app.py

示例14: _wrap_profiling

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def _wrap_profiling(self, runner, *args):
    if not self._vars.PEX_PROFILE and self._vars.PEX_PROFILE_FILENAME is None:
      return runner(*args)

    pex_profile_filename = self._vars.PEX_PROFILE_FILENAME
    pex_profile_sort = self._vars.PEX_PROFILE_SORT
    try:
      import cProfile as profile
    except ImportError:
      import profile

    profiler = profile.Profile()

    try:
      return profiler.runcall(runner, *args)
    finally:
      if pex_profile_filename is not None:
        profiler.dump_stats(pex_profile_filename)
      else:
        profiler.print_stats(sort=pex_profile_sort) 
开发者ID:pantsbuild,项目名称:pex,代码行数:22,代码来源:pex.py

示例15: symm_inner_product_array

# 需要导入模块: import cProfile [as 别名]
# 或者: from cProfile import Profile [as 别名]
def symm_inner_product_array(
    num_states, num_vecs, max_vecs_per_node, verbosity=1):
    """
    Computes symmetric inner product array from known vecs (as in POD).
    """
    vec_handles = [mr.VecHandlePickle(join(data_dir, row_vec_name%row_num))
        for row_num in mr.range(num_vecs)]

    generate_vecs(data_dir, num_states, vec_handles)

    my_VS = mr.VectorSpaceHandles(
        inner_product=np.vdot, max_vecs_per_node=max_vecs_per_node,
        verbosity=verbosity)

    prof = cProfile.Profile()
    start_time = time.time()
    prof.runcall(my_VS.compute_symm_inner_product_array, vec_handles)
    total_time = time.time() - start_time
    prof.dump_stats('IP_symm_array_r%d.prof'%mr.parallel.get_rank())

    return total_time 
开发者ID:belson17,项目名称:modred,代码行数:23,代码来源:benchmark.py


注:本文中的cProfile.Profile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。