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

Python statprof.stop函数代码示例

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

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



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

示例1: 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


示例2: __exit__

 def __exit__(self, type, value, callback):
     import statprof
     statprof.stop()
     for call in statprof.CallData.all_calls.itervalues():
         trace = _Trace(call)
         for attr in ('percent', 'cumulative', 'self'):
             self.update("{0}.{1}".format(trace.name, attr), getattr(trace, attr))
开发者ID:jdunck,项目名称:metrology,代码行数:7,代码来源:profiler.py


示例3: process_response

    def process_response(self, request, response):
        statprof.stop()
        client = get_client()
        total_samples = statprof.state.sample_count
        if total_samples == 0:
            return response

        secs_per_sample = statprof.state.accumulated_time / total_samples

        def get_struct(c):
            return ({
                'file': c.key.filename,
                'lineno': c.key.lineno,
                'function': c.key.name,
                'type': 'python'
            }, {
                'self_nsamples': c.self_sample_count,
                'cum_nsamples': c.cum_sample_count,
                'tot_nsamples': total_samples,
                'cum_time': c.cum_sample_count * secs_per_sample,
                'self_time': c.self_sample_count * secs_per_sample
            })

        client.insert_all([get_struct(c)
                           for c in statprof.CallData.all_calls.itervalues()])

        return response
开发者ID:ildus,项目名称:django-live-profiler,代码行数:27,代码来源:middleware.py


示例4: process_response

    def process_response(self, request, response):
        statprof.stop()
        client = get_client()
        total_samples = statprof.state.sample_count

        if total_samples == 0:
            return response

        secs_per_sample = statprof.state.accumulated_time / total_samples

        client.insert_all(
            [
                (
                    {"file": c.key.filename, "lineno": c.key.lineno, "function": c.key.name, "type": "python"},
                    {
                        "self_nsamples": c.self_sample_count,
                        "cum_nsamples": c.cum_sample_count,
                        "tot_nsamples": total_samples,
                        "cum_time": c.cum_sample_count * secs_per_sample,
                        "self_time": c.self_sample_count * secs_per_sample,
                    },
                )
                for c in statprof.CallData.all_calls.itervalues()
            ]
        )

        return response
开发者ID:natebeacham,项目名称:django-live-profiler,代码行数:27,代码来源:middleware.py


示例5: 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


示例6: 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


示例7: 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


示例8: 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


示例9: 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


示例10: 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


示例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: 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


示例14: 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


示例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: generateOrders


#.........这里部分代码省略.........
        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(False)
    fo.updateResourcePools()

    turn = fo.currentTurn()
    turn_uid = foAIstate.set_turn_uid()
    print "\n\n\n", "=" * 20,
    print "Starting turn %s (%s) of game: %s" % (turn, turn_uid, foAIstate.uid),
    print "=" * 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(foAIstate.character)
    print "***************************************************************************"
    print "*******  Log info for AI progress chart script. Do not modify.   **********"
    print ("Generating Orders")
    print ("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())
    print "EmpireColors: {0.colour.r} {0.colour.g} {0.colour.b} {0.colour.a}".format(empire)
    if planet:
        print "CapitalID: " + str(planet_id) + " Name: " + planet.name + " Species: " + planet.speciesName
    else:
        print "CapitalID: None Currently Name: None Species: None "
    print "***************************************************************************"
    print "***************************************************************************"

    if turn == 1:
        declare_war_on_all()
        human_player = fo.empirePlayerID(1)
        greet = diplomatic_corp.get_first_turn_greet_message()
        fo.sendChatMessage(human_player, '%s (%s): [[%s]]' % (empire.name, get_trait_name_aggression(foAIstate.character), greet))

    # 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.generate_production_orders,
                   ResourcesAI.generate_resources_orders,
                   ]

    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.stop_print_and_clear()
    turn_timer.stop_print_and_clear()
    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:MatGB,项目名称:freeorion,代码行数:101,代码来源:FreeOrionAI.py


示例17: generateOrders


#.........这里部分代码省略.........

    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:"
    for mod,  modTime in zip(timerEntries ,  times):
        print timeFmt % ((30*' '+mod)[-30:],  int(1000*modTime))
    if _timerFile:
        _timerFile.write(  _timerFileFmt% tuple( [ fo.currentTurn() ]+map(lambda x: int(1000*x),  times )) +'\n')
        _timerFile.flush()
    if _timerBucketFile:
        _timerBucketFile.write(  _timerBucketFileFmt% tuple( [ fo.currentTurn(),  (turnStartTime-_lastTurnTimestamp)*1000, (turnEndTime-turnStartTime)*1000   ]) +'\n')
        _timerBucketFile.flush()
        _lastTurnTimestamp = time()

    try:
        fo.doneTurn()
    except:
        print "Error: exception triggered and caught:  ",  traceback.format_exc()

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass
开发者ID:e-h-j,项目名称:freeorion,代码行数:101,代码来源:FreeOrionAI.py


示例18: 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


示例19: generateOrders


#.........这里部分代码省略.........
    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:
        human_player = fo.empirePlayerID(1)
        greet = diplomatic_corp.get_first_turn_greet_message()
        fo.sendChatMessage(human_player,
                           '%s (%s): [[%s]]' % (empire.name, get_trait_name_aggression(aistate.character), greet))

    aistate.prepare_for_new_turn()
    turn_state.state.update()
    debug("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.generate_production_orders,
                   ResourcesAI.generate_resources_orders,
                   ]

    for action in action_list:
        try:
            main_timer.start(action.__name__)
            action()
            main_timer.stop()
        except Exception as e:
            error("Exception %s while trying to %s" % (e, action.__name__), exc_info=True)
    main_timer.stop_print_and_clear()
    turn_timer.stop_print_and_clear()

    debug('Size of issued orders: ' + str(fo.getOrders().size))

    turn_timer.start("Server_Processing")

    try:
        fo.doneTurn()
    except Exception as e:
        error("Exception %s while trying doneTurn()" % e, exc_info=True)  # TODO move it to cycle above
    finally:
        aistate.last_turn_played = fo.currentTurn()

    if using_statprof:
        try:
            statprof.stop()
            statprof.display()
            statprof.start()
        except:
            pass
开发者ID:adrianbroher,项目名称:freeorion,代码行数:101,代码来源:FreeOrionAI.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.stop函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python stats.mean函数代码示例发布时间:2022-05-27
下一篇:
Python statprof.start函数代码示例发布时间: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