• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python statprof.start函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中statprof.start函数的典型用法代码示例。如果您正苦于以下问题:Python start函数的具体用法?Python start怎么用?Python start使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: worker

def worker(options):
    """
    Start background worker process.
    """
    workerPid = os.getpid()

    if not options.noaffinity:
        p = psutil.Process(workerPid)
        print "affinity [before]", p.cpu_affinity()
        p.cpu_affinity([options.cpuid])
        print "affinity [after]", p.cpu_affinity()

    factory = EchoServerFactory(options.wsuri)

    # The master already created the socket, just start listening and accepting
    ##
    reactor.adoptStreamPort(options.fd, AF_INET, factory)

    if not options.silence:
        print "Worker started on PID %s using factory %s and protocol %s" % (workerPid, factory, factory.protocol)
        # print "Worker %d PYPYLOG=%s" % (workerPid, os.environ.get('PYPYLOG', None))

    if options.profile:
        statprof.reset(PROFILER_FREQ)
        statprof.start()

    if not options.silence:
        def stat():
            if options.profile:
                statprof.stop()

            output = StringIO.StringIO()
            output.write("-" * 80 + "\n")
            output.write("Worker Statistics (PID %s)\n\n%s" % (workerPid, factory.stats.stats()))

            if options.profile:
                output.write("\n")
                # format = statprof.DisplayFormats.ByLine
                # format = statprof.DisplayFormats.ByMethod
                # statprof.display(output, format = format)
                statprof.display(output)

            output.write("-" * 80 + "\n\n")

            sys.stdout.write(output.getvalue())

            if options.profile:
                statprof.reset(PROFILER_FREQ)
                statprof.start()

            reactor.callLater(options.interval, stat)

        reactor.callLater(options.interval, stat)

    if False:
        import cProfile
        print "RUNNING cProfile"
        cProfile.run('reactor.run()')
    else:
        reactor.run()
开发者ID:Breezy1373,项目名称:autobahn-python,代码行数:60,代码来源:server.py


示例2: wrapped

 def wrapped(*args, **kwargs):
     statprof.start()
     try:
         return main(*args, **kwargs)
     finally:
         statprof.stop()
         statprof.display(OUT=file(output_file, 'wb'))
开发者ID:offlinehacker,项目名称:flumotion,代码行数:7,代码来源:boot.py


示例3: stat

      def stat():
         if options.profile:
            statprof.stop()

         output = StringIO.StringIO()
         output.write("-" * 80)
         output.write("\nWorker with PID %s processed %d requests\n"  % (workerPid, site.cnt))

         if options.profile:
            output.write("\n")
            #format = statprof.DisplayFormats.ByLine
            #format = statprof.DisplayFormats.ByMethod
            #statprof.display(output, format = format)
            statprof.display(output)

         output.write("-" * 80)
         output.write("\n")
         output.write("\n")

         sys.stdout.write(output.getvalue())

         if options.profile:
            statprof.reset()
            statprof.start()

         reactor.callLater(options.interval, stat)
开发者ID:luodaobin,项目名称:scratchbox,代码行数:26,代码来源:server.py


示例4: __enter__

 def __enter__(self):
     try:
         statprof.reset(self.frequency)
     except AssertionError:
         pass  # statprof is already running
     statprof.start()
     return self
开发者ID:Motoma,项目名称:metrology,代码行数:7,代码来源:profiler.py


示例5: inner

 def inner(*args, **kwargs):
     statprof.reset(frequency=1000)
     statprof.start()
     try:
         return fn(*args, **kwargs)
     finally:
         statprof.stop()
         statprof.display()
开发者ID:lopuhin,项目名称:python-adagram,代码行数:8,代码来源:utils.py


示例6: catching

 def catching(proc, *args, **kwargs):
     import statprof
     statprof.start()
     try:
         return proc(*args, **kwargs)
     finally:
         statprof.stop()
         statprof.display()
开发者ID:flyapen,项目名称:UgFlu,代码行数:8,代码来源:boot.py


示例7: pilot_detail

def pilot_detail(request, pilot_id):
    return pilot_detail_view.pilot_detail(request, pilot_id)
    statprof.start()
    try:
        return pilot_detail_view.pilot_detail(request, pilot_id)
    finally:
        statprof.stop()
        statprof.display()
    return pilot_detail_view.pilot_detail(request, pilot_id)
    return render(request, "analizer/index.html", {"error_message": "Unsupported: "})
开发者ID:despair1,项目名称:zk_dj,代码行数:10,代码来源:views.py


示例8: inner

 def inner(*args, **kwargs):
     if deco_kwargs.get('traceback'):
         traceback.print_stack()
     print('starting %s' % fn.__name__)
     start = time.time()
     stat_profile = deco_kwargs.get('stat_profile')
     if stat_profile:
         import statprof
         statprof.reset(frequency=10000)
         statprof.start()
     fn(*args, **kwargs)
     fn_time = time.time() - start
     print('finished %s in %s s' % (fn.__name__, fn_time))
     if stat_profile:
         statprof.stop()
         statprof.display()
     return fn_time
开发者ID:chtd,项目名称:psycopg2-benchmarks,代码行数:17,代码来源:utils.py


示例9: statprofile

def statprofile(ui, func, fp):
    try:
        import statprof
    except ImportError:
        raise util.Abort(_('statprof not available - install using "easy_install statprof"'))

    freq = ui.configint("profiling", "freq", default=1000)
    if freq > 0:
        statprof.reset(freq)
    else:
        ui.warn(_("invalid sampling frequency '%s' - ignoring\n") % freq)

    statprof.start()
    try:
        return func()
    finally:
        statprof.stop()
        statprof.display(fp)
开发者ID:CSCI-362-02-2015,项目名称:RedTeam,代码行数:18,代码来源:dispatch.py


示例10: main

def main(args):
    parser = OptionParser(domain="flumotion-job")

    log.debug('job', 'Parsing arguments (%r)' % ', '.join(args))
    options, args = parser.parse_args(args)

    # check if a config file was specified; if so, parse config and copy over
    if len(args) != 3:
        parser.error("must pass an avatarId and a path to the socket: %r" %
            args)
    avatarId = args[1]
    socket = args[2]

    # log our standardized starting marker
    log.info('job', "Starting job '%s'" % avatarId)

    # register all package paths (FIXME: this should go away when
    # components and all deps come from manager)
    # this is still necessary so that code from other projects can be imported
    from flumotion.common import setup
    setup.setupPackagePath()

    log.info('job', 'Connecting to worker on socket %s' % (socket))

    job_factory = job.JobClientFactory(avatarId)
    reactor.connectWith(fdserver.FDConnector, socket, job_factory,
        10, checkPID=False)

    # should probably move this to boot
    if 'FLU_PROFILE' in os.environ:
        try:
            import statprof
            statprof.start()
            print 'Profiling started.'

            def stop_profiling():
                statprof.stop()
                statprof.display()

            reactor.addSystemEventTrigger('before', 'shutdown',
                stop_profiling)
        except ImportError, e:
            print ('Profiling requested, but statprof is not available (%s)'
                   % e)
开发者ID:flyapen,项目名称:UgFlu,代码行数:44,代码来源:main.py


示例11: run

def run(main, profile=None):
    if not profile:
        main()
        return

    if profile == 'hotshot':
        import hotshot, hotshot.stats
        p = hotshot.Profile("/tmp/pro")
        p.runcall(main)
        p.close()
        hotshot.stats.load("/tmp/pro").sort_stats('cumulative').print_stats()
    elif profile == 'stat':
        import statprof
        statprof.start()
        try:
            main()
        finally:
            statprof.stop()
            statprof.display()
开发者ID:drewp,项目名称:light9,代码行数:19,代码来源:prof.py


示例12: statprofile

def statprofile(ui, fp):
    try:
        import statprof
    except ImportError:
        raise error.Abort(_(
            'statprof not available - install using "easy_install statprof"'))

    freq = ui.configint('profiling', 'freq', default=1000)
    if freq > 0:
        # Cannot reset when profiler is already active. So silently no-op.
        if statprof.state.profile_level == 0:
            statprof.reset(freq)
    else:
        ui.warn(_("invalid sampling frequency '%s' - ignoring\n") % freq)

    statprof.start()
    try:
        yield
    finally:
        statprof.stop()
        statprof.display(fp)
开发者ID:motlin,项目名称:cyg,代码行数:21,代码来源:profiling.py


示例13: stat

      def stat():
         if options.profile:
            statprof.stop()

         output = StringIO.StringIO()
         output.write("-" * 80 + "\n")
         output.write("Worker Statistics (PID %s)\n\n%s"  % (workerPid, factory.stats.stats()))

         if options.profile:
            output.write("\n")
            #format = statprof.DisplayFormats.ByLine
            #format = statprof.DisplayFormats.ByMethod
            #statprof.display(output, format = format)
            statprof.display(output)

         output.write("-" * 80 + "\n\n")

         sys.stdout.write(output.getvalue())

         if options.profile:
            statprof.reset(PROFILER_FREQ)
            statprof.start()

         reactor.callLater(options.interval, stat)
开发者ID:EricSchles,项目名称:AutobahnPython,代码行数:24,代码来源:server.py


示例14: test_profiling_output_contains_file_names_formatted_appropriately

def test_profiling_output_contains_file_names_formatted_appropriately():
    start()

    def fun():
        for i in range(2 ** 20):
            pass

    def fun2():
        for i in range(50):
            fun()

    fun2()
    stop()

    for format in (DisplayFormat.BY_LINE, DisplayFormat.BY_METHOD):
        full_path = abspath(__file__)
        base = basename(__file__)

        content = get_output(format=format, path_format=PathFormat.FULL_PATH)
        assert full_path in content

        content = get_output(format=format, path_format=PathFormat.FILENAME_ONLY)
        assert base in content
        assert full_path not in content
开发者ID:anntzer,项目名称:statprof.py,代码行数:24,代码来源:test_statprof.py


示例15: generateOrders

def generateOrders():  # pylint: disable=invalid-name
    """Called once per turn to tell the Python AI to generate and issue orders to control its empire.
    at end of this function, fo.doneTurn() should be called to indicate to the client that orders are finished
    and can be sent to the server for processing."""
    empire = fo.getEmpire()
    if empire.eliminated:
        print "This empire has been eliminated. Aborting order generation"
        try:
            # early abort if already eliminated. no need to do meter calculations
            # on last-seen gamestate if nothing can be ordered anyway...
            fo.doneTurn()
        except Exception as e:
            print_error(e)
        return

    # This code block is required for correct AI work.
    print "Meter / Resource Pool updating..."
    fo.initMeterEstimatesDiscrepancies()
    fo.updateMeterEstimates(0)
    fo.updateResourcePools()

    turn = fo.currentTurn()
    turn_uid = foAIstate.set_turn_uid()
    print "Start turn %s (%s) of game: %s" % (turn, turn_uid, foAIstate.uid)

    turn_timer.start("AI planning")
    # set the random seed (based on galaxy seed, empire name and current turn)
    # for game-reload consistency.
    random_seed = str(fo.getGalaxySetupData().seed) + "%05d%s" % (turn, fo.getEmpire().name)
    random.seed(random_seed)
    aggression_name = fo.aggression.values[foAIstate.aggression].name
    if turn == 1:
        declare_war_on_all()
        human_player = fo.empirePlayerID(1)
        fo.sendChatMessage(human_player,  '%s Empire (%s):\n"Ave, Human, morituri te salutant!"' % (empire.name, aggression_name))

    # turn cleanup !!! this was formerly done at start of every turn -- not sure why
    foAIstate.split_new_fleets()

    foAIstate.refresh()  # checks exploration border & clears roles/missions of missing fleets & updates fleet locs & threats
    foAIstate.report_system_threats()
    print("Calling AI Modules")
    # call AI modules
    action_list = [ColonisationAI.survey_universe,
                   ProductionAI.find_best_designs_this_turn,
                   PriorityAI.calculate_priorities,
                   ExplorationAI.assign_scouts_to_explore_systems,
                   ColonisationAI.assign_colony_fleets_to_colonise,
                   InvasionAI.assign_invasion_fleets_to_invade,
                   MilitaryAI.assign_military_fleets_to_systems,
                   FleetUtilsAI.generate_fleet_orders_for_fleet_missions,
                   FleetUtilsAI.issue_fleet_orders_for_fleet_missions,
                   ResearchAI.generate_research_orders,
                   ProductionAI.generateProductionOrders,
                   ResourcesAI.generate_resources_orders,
                   foAIstate.after_turn_cleanup,
                   ]

    for action in action_list:
        try:
            main_timer.start(action.__name__)
            action()
            main_timer.stop()
        except Exception as e:
            print_error(e, location=action.__name__)
    main_timer.end()
    turn_timer.end()
    turn_timer.start("Server_Processing")

    try:
        fo.doneTurn()
    except Exception as e:
        print_error(e)  # TODO move it to cycle above

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass
开发者ID:PanchoWW,项目名称:Learnorion,代码行数:81,代码来源:FreeOrionAI.py


示例16: parse_1kg

import pstats
import sys

def parse_1kg():
    for line in vcf.Reader(filename='vcf/test/1kg.vcf.gz'):
        pass

if len(sys.argv) == 1:
    sys.argv.append(None)

if sys.argv[1] == 'profile':
    cProfile.run('parse_1kg()', '1kg.prof')
    p = pstats.Stats('1kg.prof')
    p.strip_dirs().sort_stats('time').print_stats()

elif sys.argv[1] == 'time':
    n = 1
    t = timeit.timeit('parse_1kg()',  "from __main__ import parse_1kg", number=n)
    print t/n

elif sys.argv[1] == 'stat':
    import statprof
    statprof.start()
    try:
        parse_1kg()
    finally:
        statprof.stop()
        statprof.display()
else:
    print 'prof.py profile/time'
开发者ID:Ros85,项目名称:MToolBox,代码行数:30,代码来源:prof.py


示例17: generateOrders

def generateOrders(): # pylint: disable=invalid-name
    "called by client to get the AI's orders for the turn"
    global _lastTurnTimestamp
    universe = fo.getUniverse()
    turnStartTime = time() #starting AI timer here, to be sure AI doesn't get blame for any  lags in server being able to provide the Universe object
    empire = fo.getEmpire()
    planetID = PlanetUtilsAI.getCapital()
    planet = None
    if planetID is not None:
        planet = universe.getPlanet(planetID)
    print "***************************************************************************"
    print "***************************************************************************"
    print ("Generating Orders")
    print "EmpireID:    " + str(empire.empireID) + " Name: " + empire.name+ "_"+str(empire.empireID) +"_pid:"+str(fo.playerID())+"_"+fo.playerName()+"_"+_aggressions.get(foAIstate.aggression,  "?") + " Turn: " + str(fo.currentTurn())
    empireColor = empire.colour
    print "EmpireColors: %d %d %d %d"% (empireColor.r,  empireColor.g,  empireColor.b,  empireColor.a)
    if planet:
        print "CapitalID: " + str(planetID) + " Name: " + planet.name + " Species: " + planet.speciesName
    else:
        print "CapitalID: None Currently      Name: None     Species: None "
    print "***************************************************************************"
    print "***************************************************************************"

    if fo.currentTurn() == 1:
        declareWarOnAll()

    # turn cleanup !!! this was formerly done at start of every turn -- not sure why
    splitNewFleets()

    #updateShipDesigns()   #should not be needed anymore;
    #updateFleetsRoles()

    foAIstate.clean() #checks exploration border & clears roles/missions of missing fleets & updates fleet locs
    foAIstate.reportSystemThreats()
    # ...missions
    # ...demands/priorities

    print("Calling AI Modules")

    # call AI modules
    timer = [time()]
    try:
        PriorityAI.calculatePriorities()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc() # try traceback.print_exc()
    timer.append( time()  )
    try:
        ExplorationAI.assignScoutsToExploreSystems()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        ColonisationAI.assignColonyFleetsToColonise()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        InvasionAI.assignInvasionFleetsToInvade()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        MilitaryAI.assignMilitaryFleetsToSystems()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        FleetUtilsAI.generateAIFleetOrdersForAIFleetMissions()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        FleetUtilsAI.issueAIFleetOrdersForAIFleetMissions()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        ResearchAI.generateResearchOrders()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        ProductionAI.generateProductionOrders()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        ResourcesAI.generateResourcesOrders()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    try:
        foAIstate.afterTurnCleanup()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()
    timer.append( time()  )
    times = [timer[i] - timer[i-1] for i in range(1,  len(timer) ) ]
    turnEndTime = time()
    timeFmt = "%30s: %8d msec  "
    print "AI Module Time Requirements:"
#.........这里部分代码省略.........
开发者ID:e-h-j,项目名称:freeorion,代码行数:101,代码来源:FreeOrionAI.py


示例18: generateOrders

def generateOrders():  # pylint: disable=invalid-name
    """Called once per turn to tell the Python AI to generate and issue orders to control its empire.
    at end of this function, fo.doneTurn() should be called to indicate to the client that orders are finished
    and can be sent to the server for processing."""
    try:
        rules = fo.getGameRules()
        debug("Defined game rules:")
        for rule_name, rule_value in rules.getRulesAsStrings().items():
            debug("%s: %s", rule_name, rule_value)
        debug("Rule RULE_NUM_COMBAT_ROUNDS value: " + str(rules.getInt("RULE_NUM_COMBAT_ROUNDS")))
    except Exception as e:
        error("Exception %s when trying to get game rules" % e, exc_info=True)

    empire = fo.getEmpire()
    if empire is None:
        fatal("This client has no empire. Doing nothing to generate orders.")
        try:
            # early abort if no empire. no need to do meter calculations
            # on last-seen gamestate if nothing can be ordered anyway...
            #
            # note that doneTurn() is issued on behalf of the client network
            # id, not the empire id, so not having a correct empire id does
            # not invalidate doneTurn()
            fo.doneTurn()
        except Exception as e:
            error("Exception %s in doneTurn() on non-existent empire" % e, exc_info=True)
        return

    if empire.eliminated:
        debug("This empire has been eliminated. Aborting order generation")
        try:
            # early abort if already eliminated. no need to do meter calculations
            # on last-seen gamestate if nothing can be ordered anyway...
            fo.doneTurn()
        except Exception as e:
            error("Exception %s while trying doneTurn() on eliminated empire" % e, exc_info=True)
        return

    # This code block is required for correct AI work.
    info("Meter / Resource Pool updating...")
    fo.initMeterEstimatesDiscrepancies()
    fo.updateMeterEstimates(False)
    fo.updateResourcePools()

    turn = fo.currentTurn()
    aistate = get_aistate()
    turn_uid = aistate.set_turn_uid()
    debug("\n\n\n" + "=" * 20)
    debug("Starting turn %s (%s) of game: %s" % (turn, turn_uid, aistate.uid))
    debug("=" * 20 + "\n")

    turn_timer.start("AI planning")
    # set the random seed (based on galaxy seed, empire name and current turn)
    # for game-reload consistency.
    random_seed = str(fo.getGalaxySetupData().seed) + "%05d%s" % (turn, fo.getEmpire().name)
    random.seed(random_seed)

    universe = fo.getUniverse()
    empire = fo.getEmpire()
    planet_id = PlanetUtilsAI.get_capital()
    planet = None
    if planet_id is not None:
        planet = universe.getPlanet(planet_id)
    aggression_name = get_trait_name_aggression(aistate.character)
    debug("***************************************************************************")
    debug("*******  Log info for AI progress chart script. Do not modify.   **********")
    debug("Generating Orders")
    debug("EmpireID: {empire.empireID}"
          " Name: {empire.name}_{empire.empireID}_pid:{p_id}_{p_name}RIdx_{res_idx}_{aggression}"
          " Turn: {turn}".format(empire=empire, p_id=fo.playerID(), p_name=fo.playerName(),
                                 res_idx=ResearchAI.get_research_index(), turn=turn,
                                 aggression=aggression_name.capitalize()))
    debug("EmpireColors: {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}".format(empire))
    if planet:
        debug("CapitalID: " + str(planet_id) + " Name: " + planet.name + " Species: " + planet.speciesName)
    else:
        debug("CapitalID: None Currently Name: None Species: None ")
    debug("***************************************************************************")
    debug("***************************************************************************")

    # When loading a savegame, the AI will already have issued orders for this turn.
    # To avoid duplicate orders, generally try not to replay turns. However, for debugging
    # purposes it is often useful to replay the turn and observe varying results after
    # code changes. Set the replay_after_load flag in the AI config to let the AI issue
    # new orders after a game load. Note that the orders from the original savegame are
    # still being issued and the AIstate was saved after those orders were issued.
    # TODO: Consider adding an option to clear AI orders after load (must save AIstate at turn start then)
    if fo.currentTurn() == aistate.last_turn_played:
        info("The AIstate indicates that this turn was already played.")
        if not check_bool(get_option_dict().get('replay_turn_after_load', 'False')):
            info("Aborting new order generation. Orders from savegame will still be issued.")
            try:
                fo.doneTurn()
            except Exception as e:
                error("Exception %s while trying doneTurn()" % e, exc_info=True)
            return
        else:
            info("Issuing new orders anyway.")

    if turn == 1:
#.........这里部分代码省略.........
开发者ID:adrianbroher,项目名称:freeorion,代码行数:101,代码来源:FreeOrionAI.py


示例19: process_request

 def process_request(self, request):
     statprof.reset(getattr(settings, 'LIVEPROFILER_STATPROF_FREQUENCY', 100))
     statprof.start()
开发者ID:mdebski,项目名称:django-live-profiler,代码行数:3,代码来源:middleware.py


示例20: rep_bench

def rep_bench(func, n, runtime=None, initfunc=None, runreps=None, runiters=10, profile=False, profresults="pyutil-benchutil.prof", UNITS_PER_SECOND=1, quiet=False):
    """
    @param quiet Don't print anything--just return the results dict.
    @param runtime How many seconds to run the inner loop (for measuring the time of the code-under-measurement). If None then do it runreps times regardless of how many seconds it takes.
    @param runreps How many times to run the inner loop (for measuring the time of the code-under-measurement). If None then do it until runtime seconds have passed.
    @param runiters How many times to run the outer loop (for generating statistics about the distribution of runtimes of the code-under-measurement).
    """
    assert isinstance(n, int), (n, type(n))
    assert (runtime is None) != (runreps is None), "Choose either runtime mode or runreps mode. runtime: %s, runreps: %s" % (runtime, runreps,)

    global worstemptymeasure
    if runtime is not None:
        (time_per_rep, reps) = _measure_empty_func_with_runtime(profile=profile)
        if time_per_rep * MARGINOFERROR >= runtime:
            raise BadMeasure("Apparently simply invoking an empty Python function can take as long as %0.10f seconds, and we were running reps for only about %0.10f seconds. So the measurement of the runtime of the code under benchmark is not reliable. Please pass a higher number for the 'runtime' argument to rep_bench().")
    else:
        (time_per_rep, reps) = _measure_empty_func_with_reps(profile=profile)
        if (worstemptymeasure is None) or (time_per_rep > worstemptymeasure):
            worstemptymeasure = time_per_rep

    tls = [] # (elapsed time per rep in seconds, numreps)
    while len(tls) < runiters:
        if initfunc:
            initfunc(n)
        if profile:
            import statprof
            statprof.start()
            try:
                tl, reps = bench_it(func, n, runtime=runtime, runreps=runreps)
            finally:
                statprof.stop()
        else:
            tl, reps = bench_it(func, n, runtime=runtime, runreps=runreps)
        tls.append((tl, reps))
    sumtls = sum([tl for (tl, reps) in tls])
    mean = sumtls / len(tls)
    tls.sort()
    worst = tls[-1][0]
    best = tls[0][0]

    if best < (worstemptymeasure * MARGINOFERROR):
        raise BadMeasure("Apparently simply invoking an empty Python function can take as long as %0.10f seconds, and we were running reps for only about %0.10f seconds. So the measurement of the runtime of the code under benchmark is not reliable. Please pass a higher number for the 'runtime' argument to rep_bench().")

    m = len(tls)/4
    if m > 0:
        mthbest = tls[m-1][0]
        mthworst = tls[-m][0]
    else:
        mthbest = tls[0][0]
        mthworst = tls[-1][0]

    # The +/-0 index is the best/worst, the +/-1 index is the 2nd-best/worst,
    # etc, so we use mp1 to name it.
    mp1 = m+1
    res = {
        'worst': mult(worst, UNITS_PER_SECOND)/n,
        'best': mult(best, UNITS_PER_SECOND)/n,
        'mp1': mp1,
        'mth-best': mult(mthbest, UNITS_PER_SECOND)/n,
        'mth-worst': mult(mthworst, UNITS_PER_SECOND)/n,
        'mean': mult(mean, UNITS_PER_SECOND)/n,
        'num': len(tls),
        }

    if not quiet:
        print "best: %(best)#8.03e, %(mp1)3dth-best: %(mth-best)#8.03e, mean: %(mean)#8.03e, %(mp1)3dth-worst: %(mth-worst)#8.03e, worst: %(worst)#8.03e (of %(num)6d)" % res

    return res
开发者ID:bingwei,项目名称:pyutil,代码行数:68,代码来源:benchutil.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python statprof.stop函数代码示例发布时间:2022-05-27
下一篇:
Python statistics.Statistics类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap