B u `£Wã@süddlZddlZddlZddlZe d¡Zde_e ej¡Gdd„de ƒZ ddd„Z e d ¡Z Gd d „d e ƒZ e d ¡ZGd d„de ƒZejdkrœejZnej d¡r°ejZnejZGdd„de ƒZeƒZejZejZGdd„de ƒZGdd„de ƒZdS)éNzpyomo.common.timingFc@s eZdZdS)Ú _NotSpecifiedN)Ú__name__Ú __module__Ú __qualname__©rrú7/tmp/pip-unpacked-wheel-n62dbgi3/pyomo/common/timing.pyrsrTcCsp|rFt tj¡|dkrtj}t |¡}| t d¡¡t  |¡|St tj ¡xtj D]}t  |¡qZWdS)NTz %(message)s) Ú_loggerÚsetLevelÚloggingÚINFOÚsysÚstdoutÚ StreamHandlerÚ setFormatterÚ FormatterÚ addHandlerÚWARNINGÚhandlersÚ removeHandler)ÚstreamÚhandlerÚhrrrÚ report_timings     rz pyomo.common.timing.constructionc@s(eZdZdZdd„Zdd„Zdd„ZdS) ÚConstructionTimerz/%%6.%df seconds to construct %s %s; %d %s totalcCs||_tƒ|_dS)N)ÚobjÚ TicTocTimerÚtimer)ÚselfrrrrÚ__init__1szConstructionTimer.__init__cCs|jjdd|_t |¡dS)N)Úmsg)rÚtocÚ_construction_loggerÚinfo)rrrrÚreport5szConstructionTimer.reportc Cs|j}yt|j ¡ƒ}Wntk r0d}YnXy |jj}WnPtk rxy |jj}Wntk rrd}YnXYntk rŽd}YnXy|jjj }Wn tk r¾t |jƒj }YnXy0|j |dkrÒdnd||||dkrædndf|St k rd|||j  d ¡fSXdS) Néz (unknown)g{®Gázt?érÚindicesÚindexz6ConstructionTimer object for %s %s; %s elapsed secondsÚ)rÚlenrZ index_setÚAttributeErrorÚnameÚ RuntimeErrorZ local_nameÚctyperÚtypeÚfmtÚ TypeErrorr )rÚ total_timeÚidxr+Ú_typerrrÚ__str__;s2    0zConstructionTimer.__str__N)rrrr/rr#r4rrrrr/srz"pyomo.common.timing.transformationc@s*eZdZdZd dd„Zdd„Zdd„ZdS) ÚTransformationTimerz,%%6.%df seconds to apply Transformation %s%sNcCs.||_|dkrd|_n d|f|_tƒ|_dS)Nr(z (%s))rÚmoderr)rrr6rrrras  zTransformationTimer.__init__cCs|jjdd|_t |¡dS)N)r)rr Ú_transform_loggerr")rrrrr#iszTransformationTimer.reportcCs\|j}|jjj}y"|j|dkr"dnd||jf|Stk rVd||j d¡fSXdS)Ng{®Gázt?r%rz5TransformationTimer object for %s; %s elapsed secondsr()rrÚ __class__rr/r6r0r )rr1r+rrrr4os "zTransformationTimer.__str__)N)rrrr/rr#r4rrrrr5_s r5)ér9Úwinc@sPeZdZdZedfdd„Zeeefdd„Zedeefdd „Zd d „Zd d „Z dS)ra†A class to calculate and report elapsed time. Examples: >>> from pyomo.common.timing import TicTocTimer >>> timer = TicTocTimer() >>> timer.tic('starting timer') # starts the elapsed time timer (from 0) >>> # ... do task 1 >>> timer.toc('task 1') # prints the elapsed time for task 1 If no ostream or logger is provided, then output is printed to sys.stdout Args: ostream (FILE): an optional output stream to print the timing information logger (Logger): an optional output stream using the python logging package. Note: timing logged using logger.info NcCs*tƒ|_|_||_||_d|_d|_dS)Nr)Ú default_timerÚ _lastTimeÚ _loadTimeÚostreamÚloggerÚ _start_countÚ_cumul)rr>r?rrrr s zTicTocTimer.__init__cCs2tƒ|_|tkrd}|dk r.|j|d||ddS)aÔReset the tic/toc delta timer. This resets the reference time from which the next delta time is calculated to the current time. Args: msg (str): The message to print out. If not specified, then prints out "Resetting the tic/toc delta timer"; if msg is None, then no message is printed. ostream (FILE): an optional output stream (overrides the ostream provided when the class was constructed). logger (Logger): an optional output stream using the python logging package (overrides the ostream provided when the class was constructed). Note: timing logged using logger.info z!Resetting the tic/toc delta timerNF)rÚdeltar>r?)r;r<rr )rrr>r?rrrÚtic§s zTicTocTimer.ticTcCs$|tkr$dtjddddd…}tƒ}|js:|jdkrp|j}|jrV|tƒ|j7}|dk r¸d||j|f}nH|rš||j}||_|dk r¸d||f}n||j}|dk r¸d ||f}|dk r |tkrÐ|j}|dk râ|  |¡|tkr |j }|tkr |dkr t j }|dk r |  |¡|S) aðPrint out the elapsed time. This resets the reference time from which the next delta time is calculated to the current time. Args: msg (str): The message to print out. If not specified, then print out the file name, line number, and function that called this method; if msg is None, then no message is printed. delta (bool): print out the elapsed wall clock time since the last call to :meth:`tic` or :meth:`toc` (:const:`True` (default)) or since the module was first loaded (:const:`False`). ostream (FILE): an optional output stream (overrides the ostream provided when the class was constructed). logger (Logger): an optional output stream using the python logging package (overrides the ostream provided when the class was constructed). Note: timing logged using logger.info zFile "%s", line %s in %sr%)ÚlimitrNr9z[%8.2f|%4d] %s z [+%7.2f] %s z [%8.2f] %s )rÚ tracebackÚ extract_stackr;r@r<rAr=r?r"r>r r Úwrite)rrrBr>r?ÚnowZansrrrr Às<        zTicTocTimer.toccCsRytƒ|j}Wn(tk r8|jdkr2tdƒ‚‚YnX|j|7_d|_|S)Nz/Stopping a TicTocTimer that was already stopped)r;r<r0r,rA)rrBrrrÚstopüs zTicTocTimer.stopcCs(|jr| ¡|jd7_tƒ|_dS)Nr$)r<rIr@r;)rrrrÚstartszTicTocTimer.start) rrrÚ__doc__rrrCr rIrJrrrrrŽs; rc@s4eZdZdd„Zdd„Zdd„Zdd„Zd d „Zd S) Ú_HierarchicalHelpercCs tƒ|_tƒ|_d|_d|_dS)Nr)rÚtic_tocÚdictÚtimersr1Ún_calls)rrrrrsz_HierarchicalHelper.__init__cCs|jd7_|j ¡dS)Nr$)rPrMrJ)rrrrrJsz_HierarchicalHelper.startcCs|j|j ¡7_dS)N)r1rMrI)rrrrrIsz_HierarchicalHelper.stopc CsNd}t|jƒdkrJ|dt|ƒdd}||7}dtt|ƒƒd}|j}|dd…}x–t|j ¡ƒD]„\}} |jdkrŽ| j|jd } ntd ƒ} ||7}||d j|| j | j| j| j | d 7}|| j |d |d|d7}|| j8}qjW|jdkr||jd } ntd ƒ} ||7}||djdd|d| d 7}||  dd¡7}|S)Nr(rú-é$Ú z{name:<Ú}r$édÚnanz={ncalls:>9d} {cumtime:>9.3f} {percall:>9.3f} {percent:>6.1f} )r+ÚncallsÚcumtimeÚpercallÚpercentú )ÚindentÚstage_identifier_lengthsz9{ncalls:>9} {cumtime:>9.3f} {percall:>9} {percent:>6.1f} Úotherzn/aú=) r)rOÚsumÚstrr1ÚsortedÚitemsÚfloatÚformatrPÚto_strÚreplace) rr\r]ÚsÚ underlineÚname_formatterZ other_timeÚsub_stage_identifier_lengthsr+rZ_percentrrrrf!sD         z_HierarchicalHelper.to_strcCs>x8|j ¡D]*\}}|d|}| |¡| ||¡q WdS)NÚ.)rOrcÚappendÚ get_timers)rÚresÚprefixr+rÚ_namerrrrnJs  z_HierarchicalHelper.get_timersN)rrrrrJrIrfrnrrrrrLs )rLc@szeZdZdZdd„Zddd„Zdd„Zd d „Zd d „Zd d„Z dd„Z dd„Z dd„Z dd„Z dd„Zdd„Zdd„ZdS)ÚHierarchicalTimeraÍ A class for hierarchical timing. Examples -------- >>> import time >>> from pyomo.common.timing import HierarchicalTimer >>> timer = HierarchicalTimer() >>> timer.start('all') >>> time.sleep(0.2) >>> for i in range(10): ... timer.start('a') ... time.sleep(0.1) ... for i in range(5): ... timer.start('aa') ... time.sleep(0.01) ... timer.stop('aa') ... timer.start('ab') ... timer.stop('ab') ... timer.stop('a') ... >>> for i in range(10): ... timer.start('b') ... time.sleep(0.02) ... timer.stop('b') ... >>> timer.stop('all') >>> print(timer) Identifier ncalls cumtime percall % --------------------------------------------------- all 1 2.248 2.248 100.0 ---------------------------------------------- a 10 1.787 0.179 79.5 ----------------------------------------- aa 50 0.733 0.015 41.0 ab 10 0.000 0.000 0.0 other n/a 1.055 n/a 59.0 ========================================= b 10 0.248 0.025 11.0 other n/a 0.213 n/a 9.5 ============================================== =================================================== The columns are: ncalls : The number of times the timer was started and stopped cumtime: The cumulative time (in seconds) the timer was active (started but not stopped) percall: cumtime (in seconds) / ncalls % : This is cumtime of the timer divided by cumtime of the parent timer times 100 >>> print('a total time: %f' % timer.get_total_time('all.a')) a total time: 1.902037 >>> print('ab num calls: %d' % timer.get_num_calls('all.a.ab')) ab num calls: 10 >>> print('aa %% time: %f' % timer.get_relative_percent_time('all.a.aa')) aa % time: 44.144148 >>> print('aa %% total: %f' % timer.get_total_percent_time('all.a.aa')) aa % total: 35.976058 Internal Workings ----------------- The HierarchicalTimer use a stack to track which timers are active at any point in time. Additionally, each timer has a dictionary of timers for its children timers. Consider >>> timer = HierarchicalTimer() >>> timer.start('all') >>> timer.start('a') >>> timer.start('aa') After the above code is run, self.stack will be ['all', 'a', 'aa'] and self.timers will have one key, 'all' and one value which will be a _HierarchicalHelper. The _HierarchicalHelper has its own timers dictionary: {'a': _HierarchicalHelper} and so on. This way, we can easily access any timer with something that looks like the stack. The logic is recursive (although the code is not). cCstƒ|_tƒ|_dS)N)ÚlistÚstackrNrO)rrrrr¦szHierarchicalTimer.__init__FcCsZ| |j¡}||jkr |j|S|r@td d |j|g¡¡ƒ‚tƒ|j|<|j|SdS)a This method gets the timer associated with the current state of self.stack and the specified identifier. Parameters ---------- identifier: str The name of the timer should_exist: bool The should_exist is True, and the timer does not already exist, an error will be raised. If should_exist is False, and the timer does not already exist, a new timer will be made. Returns ------- timer: _HierarchicalHelper zCould not find timer {0}rlN)Ú_get_timer_from_stackrtrOr,reÚjoinrL)rÚ identifierÚ should_existÚparentrrrÚ _get_timerªs    zHierarchicalTimer._get_timercCs"| |¡}| ¡|j |¡dS)zª Start incrementing the timer identified with identifier Parameters ---------- identifier: str The name of the timer N)rzrJrtrm)rrwrrrrrJÉs zHierarchicalTimer.startcCsN||jdkr*tt|ƒdd |j¡ƒ‚|j ¡|j|dd}| ¡dS)z© Stop incrementing the timer identified with identifier Parameters ---------- identifier: str The name of the timer éÿÿÿÿzU is not the currently active timer. The only timer that can currently be stopped is rlT)rxN)rtÚ ValueErrorrarvÚpoprzrI)rrwrrrrrIÖs  zHierarchicalTimer.stopcCs‚t|j ¡ƒ}tƒ}xht|ƒdkr|tƒ}d}x4|D],\}}| |j ¡¡t|ƒ|kr2t|ƒ}q2W| t|tdƒƒ¡|}qW|S)Nrr^)rsrOrcr)ÚextendrmÚmax)rZ stage_timersZ stage_lengthsZnew_stage_timersÚmax_lenrwrrrrÚ_get_identifier_lenès  z%HierarchicalTimer._get_identifier_lenc CsÔ| ¡}dtt|ƒƒd}|djdddddd }d t|ƒd d }||7}|d d…}xbt|j ¡ƒD]P\}}||dj||j|j|j|j|  |¡d 7}||j d|d|d7}qlW||  d d¡7}|S)Nz{name:9} {cumtime:>9} {percall:>9} {percent:>6} Z IdentifierrWrXrYú%)r+rWrXrYrZrQrRrSr$z={ncalls:>9d} {cumtime:>9.3f} {percall:>9.3f} {percent:>6.1f} r[r)r\r]r_) rrar`rerbrOrcrPr1Úget_total_percent_timerfrg)rr]rjrhrirkr+rrrrr4øs.    zHierarchicalTimer.__str__cCstƒ|_tƒ|_dS)z- Completely reset the timer. N)rsrtrNrO)rrrrÚresetszHierarchicalTimer.resetcCs |}x|D]}|j|}q W|S)zì This method gets the timer associated with stack. Parameters ---------- stack: list of str A list of identifiers. Returns ------- timer: _HierarchicalHelper )rO)rrtÚtmpÚirrrrus  z'HierarchicalTimer._get_timer_from_stackcCs| d¡}| |¡}|jS)a$ Parameters ---------- identifier: str The full name of the timer including parent timers separated with dots. Returns ------- total_time: float The total time spent with the specified timer active. rl)Úsplitrur1)rrwrtrrrrÚget_total_time,s  z HierarchicalTimer.get_total_timecCs| d¡}| |¡}|jS)a) Parameters ---------- identifier: str The full name of the timer including parent timers separated with dots. Returns ------- num_calss: int The number of times start was called for the specified timer. rl)r‡rurP)rrwrtrrrrÚ get_num_calls=s  zHierarchicalTimer.get_num_callscCs^| d¡}| |¡}| |dd…¡}||kr8| |¡S|jdkrR|j|jdStdƒSdS)aW Parameters ---------- identifier: str The full name of the timer including parent timers separated with dots. Returns ------- percent_time: float The percent of time spent in the specified timer relative to the timer's immediate parent. rlNr{rrUrV)r‡rurƒr1rd)rrwrtrryrrrÚget_relative_percent_timeNs    z+HierarchicalTimer.get_relative_percent_timecCsX| d¡}| |¡}d}x|j ¡D]}||j7}q$W|dkrL|j|dStdƒSdS)aW Parameters ---------- identifier: str The full name of the timer including parent timers separated with dots. Returns ------- percent_time: float The percent of time spent in the specified timer relative to the total time in all timers. rlrrUrVN)r‡rurOÚvaluesr1rd)rrwrtrr1Z_timerrrrrƒgs  z(HierarchicalTimer.get_total_percent_timecCs8tƒ}x,|j ¡D]\}}| |¡| ||¡qW|S)z~ Returns ------- identifiers: list of str Returns a list of all timer identifiers )rsrOrcrmrn)rror+rrrrrns  zHierarchicalTimer.get_timersN)F)rrrrKrrzrJrIrr4r„rurˆr‰rŠrƒrnrrrrrrQsT  rr)T)r r ÚtimerEÚ getLoggerrÚ propagater rÚobjectrrr!rr7r5Ú version_infoÚ perf_counterr;ÚplatformÚ startswithÚclockrZ _globalTimerrCr rLrrrrrrÚs0    - !  >