
    	^c                     <   d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZ ddlmZmZ ej        Zej        Zg dZh dZd Z G d	 d
          Z e            Z G d d          Z G d d          Zd Z e	j                    Zd Zd Zdad.dZd Zd Z d Z!d/dZ"ed             Z# G d d          Z$ G d d          Z%d0dZ&d  Z'd! Z(d/d"Z)d1d$Z*d2d%Z+i Z,d& Z-d' Z.d3d*Z/d+ Z0d/d,Z1e2d-k    r ej3         e1                       dS dS )4a
  
statprof is intended to be a fairly simple statistical profiler for
python. It was ported directly from a statistical profiler for guile,
also named statprof, available from guile-lib [0].

[0] http://wingolog.org/software/guile-lib/statprof/

To start profiling, call statprof.start():
>>> start()

Then run whatever it is that you want to profile, for example:
>>> import test.pystone; test.pystone.pystones()

Then stop the profiling and print out the results:
>>> stop()
>>> display()
  %   cumulative      self
 time    seconds   seconds  name
 26.72      1.40      0.37  pystone.py:79:Proc0
 13.79      0.56      0.19  pystone.py:133:Proc1
 13.79      0.19      0.19  pystone.py:208:Proc8
 10.34      0.16      0.14  pystone.py:229:Func2
  6.90      0.10      0.10  pystone.py:45:__init__
  4.31      0.16      0.06  pystone.py:53:copy
    ...

All of the numerical data is statistically approximate. In the
following column descriptions, and in all of statprof, "time" refers
to execution time (both user and system), not wall clock time.

% time
    The percent of the time spent inside the procedure itself (not
    counting children).

cumulative seconds
    The total number of seconds spent in the procedure, including
    children.

self seconds
    The total number of seconds spent in the procedure itself (not
    counting children).

name
    The name of the procedure.

By default statprof keeps the data collected from previous runs. If you
want to clear the collected data, call reset():
>>> reset()

reset() can also be used to change the sampling frequency from the
default of 1000 Hz. For example, to tell statprof to sample 50 times a
second:
>>> reset(50)

This means that statprof will sample the call stack after every 1/50 of
a second of user + system time spent running on behalf of the python
process. When your process is idle (for example, blocking in a read(),
as is the case at the listener), the clock does not advance. For this
reason statprof is not currently not suitable for profiling io-bound
operations.

The profiler uses the hash of the code object itself to identify the
procedures, so it won't confuse different procedures with the same name.
They will show up as two different rows in the output.

Right now the profiler is quite simplistic.  I cannot provide
call-graphs or other higher level information.  What you see in the
table is pretty much all there is. Patches are welcome :-)


Threading
---------

Because signals only get delivered to the main thread in Python,
statprof only profiles the main thread. However because the time
reporting function uses per-process timers, the results can be
significantly off if other threads' work patterns are not similar to the
main thread's work patterns.
    N   )open)encodingpycompat)s   starts   stops   resets   displays   profile>   util.py:checkhg.py:<module>dispatch.py:runpager.py:pagecmdcolor.py:colorcmddispatch.py:<lambda>dispatch.py:dispatchdispatch.py:_dispatchdispatch.py:_runcatchdispatch.py:checkargsextensions.py:closuredispatch.py:runcommanddispatch.py:_runcommandevolve.py:warnobserrorsc                  Z    t          j                    } | d         | d         z   | d         fS )Nr   r      )ostimes)r   s    4/usr/lib/python3/dist-packages/mercurial/statprof.pyclockr      s)    HJJE!HuQxq**    c                   @    e Zd ZddZddZd Zd Zed             ZdS )ProfileStateNc                 >    |                      |           d| _        d S )N   cpu)resettrackself	frequencys     r   __init__zProfileState.__init__   s    

9


r   c                     d| _         d | _        |rd|z  | _        nt          j        | d          sd| _        n	 d | _        d| _        g | _        d S )N)        r'   g      ?sample_intervalMbP?r   )accumulated_timelast_start_timer(   r   hasattrremaining_prof_timeprofile_levelsamplesr"   s     r   r    zProfileState.reset   sj     *# 	#&?D  !$(9:: 	#/D   #' r   c                     |d         | j         d         z
  |d         | j         d         z
  f}| j        d         |d         z   | j        d         |d         z   f| _        d S Nr   r   )r+   r*   )r#   	stop_time	increments      r   accumulate_timezProfileState.accumulate_time   sk    aL4/22aL4/22
	
 !!$y|3!!$y|3!
r   c                 P    | j         | j                 t          | j                  z  S N)r*   timeidxlenr/   r#   s    r   seconds_per_samplezProfileState.seconds_per_sample   s!    $T\2S5F5FFFr   c                      | j         dk    rdS dS )Ns   realr   r   )r!   r9   s    r   r7   zProfileState.timeidx   s    :  1qr   r6   )	__name__
__module____qualname__r%   r    r4   r:   propertyr7    r   r   r   r      sx              (
 
 
G G G   X  r   r   c                   P    e Zd Zi ZdZd Zd Zd Zed             Z	d Z
d Zd Zd	S )
CodeSite)pathlinenofunctionsourcec                     t          |t                    sJ || _        || _        t          |t                    sJ || _        d | _        d S r6   )
isinstancebytesrC   rD   rE   rF   )r#   rC   rD   rE   s       r   r%   zCodeSite.__init__   sN    $&&&&&	(E***** r   c                 T    	 | j         |j         k    o| j        |j        k    S #  Y dS xY w)NF)rD   rC   )r#   others     r   __eq__zCodeSite.__eq__   s4    	;%,.J49
3JJ	55s   " 'c                 8    t          | j        | j        f          S r6   )hashrD   rC   r9   s    r   __hash__zCodeSite.__hash__   s    T[$),---r   c                 x    ||f}	 | j         |         S # t          $ r  | |||          }|| j         |<   |cY S w xY wr6   )cacheKeyError)clsrC   rD   rE   kvs         r   getzCodeSite.get   s^    6N	9Q< 	 	 	D&(++ACIaLHHH	s    #99c                 p   | j         	 | j        dz
  }t          | j        d          5 }t	          |          D ]&\  }}||k    r|                                | _          n'd d d            n# 1 swxY w Y   n#  Y nxY w| j         d| _         | j         }t          |          |k    r|d |dz
           dz   }|S )Nr      rbr      s   ...)rF   rD   r   rC   	enumeratestripr8   )r#   lengthrD   fpilinerF   s          r   	getsourcezCodeSite.getsource   s   ;q$)U++ "r#,R== " "4;;*.**,,DK!E '" " " " " " " " " " " " " " "
{"!v;;NvzN+f4Fs.   A7 7A+A7 +A//A7 2A/3A7 7A;c                 J    t           j                            | j                  S r6   )r   rC   basenamer9   s    r   filenamezCodeSite.filename   s    w	***r   c                 >    |                                  d| j        S )N:)rc   rE   r9   s    r   skipnamezCodeSite.skipname  s    --////4==99r   N)r<   r=   r>   rQ   	__slots__r%   rL   rO   classmethodrV   r`   rc   rf   r@   r   r   rB   rB      s        E8I    . . .   [  &+ + +: : : : :r   rB   c                   .    e Zd ZdZd Zed             ZdS )Samplestacktimec                 "    || _         || _        d S r6   rk   )r#   rl   rm   s      r   r%   zSample.__init__
  s    
			r   c           	         g }|ru|                     t                              t          j        |j        j                  |j        t          j        |j        j                                       |j	        }|ut          ||          S r6   )appendrB   rV   r   sysbytesf_codeco_filenamef_linenoco_namef_backrj   )rS   framerm   rl   s       r   
from_framezSample.from_frame  s     	!LL%el&>??N%el&:;;    LE  	! eT"""r   N)r<   r=   r>   rg   r%   rh   rx   r@   r   r   rj   rj     sC        !I   # # [# # #r   rj   c                    t           j        dk    rt                      }t                               |           t           j        t           j                 }t           j                            t          	                    ||                     t          j        t          j        t           j        d           |t           _        d S d S )Nr   r'   )stater.   r   r4   r*   r7   r/   rp   rj   rx   signal	setitimerITIMER_PROFr(   r+   )signumrw   now	timestamps       r   profile_signal_handlerr   #  s    Qggc"""*5=9	V..ui@@AAA+U-BCHHH # r   c                    t                                           st                      }t                              |           t          j                    |          }t          j        t          j                 }t          j	        
                    t                              ||                     |t          _        t          j        t          j                   t                                           t                                            d S r6   )
stopthreadis_setr   rz   r4   sys_current_framesr*   r7   r/   rp   rj   rx   r+   rm   sleepr(   clear)tidr   rw   r   s       r   samplerthreadr   2  s    !! 
*ggc"""#%%c**5=9	V..ui@@AAA #
5())) !! 
* r   c                  "    t           j        dk    S Nr   )rz   r.   r@   r   r   	is_activer   F  s    ""r      threadr   c                    |t           _        t           xj        dz  c_        t           j        dk    r!t                      t           _        t           j        }dt           _        | a| dk    rRt          j        t          j        t                     t          j
        t          j        |pt           j        d           dS | dk    rt          j                    fdt          j                                                    D             d         }t%          j        t(          |fd	          t           _        t           j                                         dS dS dS )
z:Install the profiling signal handler, and start profiling.r   N   signalr'   r   c                 &    g | ]\  }}|k    |S r@   r@   ).0rT   frw   s      r   
<listcomp>zstart.<locals>.<listcomp>`  s"    MMMA!u**1***r   r   r   )targetargsname)rz   r!   r.   r   r+   r-   lastmechanismr{   SIGPROFr   r|   r}   r(   inspectcurrentframer   r   items	threadingThreadr   threadstart)	mechanismr!   rptr   rw   s       @r   r   r   M  s<   EK	1a %'$(! "	!!M&.*@AAA"C$@5+@#     )##(**EMMMM!4!6!6!<!<!>!>MMMaPC$+$C6  EL L     '   $#r   c                  r   t           xj        dz  c_        t           j        dk    rt          dk    r\t          j        t          j        dd          } t          j        t          j        t          j                   | d         t           _        nBt          dk    r7t          
                                 t           j                                         t                               t                                 dt           _        t           j                            d          }|rt'          |           t           S )z;Stop profiling, and uninstall the profiling signal handler.r   r   r   r'   r   Ns   STATPROF_DEST)rz   r.   r   r{   r|   r}   r   SIG_IGNr-   r   setr   joinr4   r   r+   r   environrV   	save_data)r   statprofpaths     r   stopr   g  s    	1aI%%"6#5sC@@CM&.&.999(+AE%%i''NNLegg&&& $'++,<== 	$l###Lr   c           	      J   t          | d          5 }|                    dt          j        z             t          j        D ]I}|j        }|j        }d |D             }|                    d|d                    |          fz             J	 d d d            d S # 1 swxY w Y   d S )N   w+s   %f %f
c                 b    g | ],}d                      |j        d|j        z  |j        g          -S )   s   %d)r   rC   rD   rE   r   ss     r   r   zsave_data.<locals>.<listcomp>  sF        

AFEAH$4ajABB  r   s   %d %s
    )r   writerz   r*   r/   rm   rl   r   )rC   filesamplerm   rl   sitess         r   r   r   |  s   	dE		 	@d

: 66777m 	@ 	@F;DLE   E JJ{dEJJu,=,=%>>????	@	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@s   A9BBBc                    t          | d                                                                          }d |d                                         D             t          _        g t          _        |dd          D ]}|                    d          }t          |d                   }|dd          }g }|D ]e}|                    d          }|                    t          
                    |d         t          |d                   |d                              ft          j                            t          ||                     d S )NrX   c                 ,    g | ]}t          |          S r@   )float)r   values     r   r   zload_data.<locals>.<listcomp>  s    IIIueEllIIIr   r   r   r   r      )r   read
splitlinessplitrz   r*   r/   r   rp   rB   rV   intrj   )	rC   linesr_   partsrm   rawsitesr   rawsite	sitepartss	            r   	load_datar     s.   u""$$//11EIIa8H8HIIIEEMabb	 2 2

5!!U1X9 	 	Ge,,ILLYq\3y|+<+<ilKK    	VE40011112 2r   c                     t           j        dk    s
J d            t          j                                         t                               |            dS )zClear out the state of the profiler.  Do not call while the
    profiler is running.

    The optional frequency argument specifies the number of samples to
    collect per second.r   s'   Can't reset() while statprof is runningN)rz   r.   rB   rQ   r   r    )r$   s    r   r    r      sM     !###%O###N	KK	r   c               #      K   t                       	 d V  t                       t                       d S # t                       t                       w xY wr6   )r   r   displayr@   r   r   profiler     sM      	GGG					 					s	   4 Ac                   N    e Zd Zd Zd Zd Zd Zd Zd Zd Z	e
d             Zd	S )
	SiteStatsc                 0    || _         d| _        d| _        d S r   )site	selfcount
totalcountr#   r   s     r   r%   zSiteStats.__init__  s    	r   c                 &    | xj         dz  c_         d S Nr   )r   r9   s    r   addselfzSiteStats.addself  s    !r   c                 &    | xj         dz  c_         d S r   )r   r9   s    r   addtotalzSiteStats.addtotal  s    1r   c                 J    | j         t          t          j                  z  dz  S Nd   )r   r8   rz   r/   r9   s    r   selfpercentzSiteStats.selfpercent  s    ~EM 2 22S88r   c                 J    | j         t          t          j                  z  dz  S r   )r   r8   rz   r/   r9   s    r   totalpercentzSiteStats.totalpercent  s    U]!3!33c99r   c                 D    | j         t                                          z  S r6   )r   rz   r:   r9   s    r   selfsecondszSiteStats.selfseconds  s    ~ 8 8 : :::r   c                 D    | j         t                                          z  S r6   )r   rz   r:   r9   s    r   totalsecondszSiteStats.totalseconds  s    !9!9!;!;;;r   c                 2   i }|D ]u}t          |j                  D ]^\  }}|                    |          }|st          |          }|||<   |                                 |dk    r|                                 _vd |                                D             S )Nr   c                     g | ]}|S r@   r@   r   s     r   r   z(SiteStats.buildstats.<locals>.<listcomp>  s    ***a***r   )rZ   rl   rV   r   r   r   values)rS   r/   statsr   r^   r   sitestats          r   
buildstatszSiteStats.buildstats  s     
	' 
	'F$V\22 	' 	'4 99T?? +(H"*E$K!!###66$$&&&	' +*5<<>>****r   N)r<   r=   r>   r%   r   r   r   r   r   r   rh   r   r@   r   r   r   r     s          
    9 9 9: : :; ; ;< < < + + [+ + +r   r   c                   *    e Zd ZdZdZdZdZdZdZdZ	dS )	DisplayFormatsr   r   r   rY   r         N)
r<   r=   r>   ByLineByMethodAboutMethodHotpath
FlameGraphJsonChromer@   r   r   r   r     s1        FHKGJDFFFr   r   rY   c                 `   |t           }| ddlm} |j        } t	          |j                  dk    r|                     d           dS |t          j        k    rt          ||            n|t          j
        k    rt          ||            n|t          j        k    rt          || fi | n|t          j        k    rt          || fi | nn|t          j        k    rt#          || fi | nO|t          j        k    rt'          ||            n.|t          j        k    rt+          || fi | nt-          d          |t          j        t          j        fvr^|                     d           |                     dt	          |j                  z             |                     d	|j        z             dS dS )
z<Print statistics, either to stdout or the given file object.Nr   )procutilr   s   No samples recorded.
zInvalid display formats   ---
s   Sample count: %d
s!   Total time: %f seconds (%f wall)
)rz   utilsr   stdoutr8   r/   r   r   r   display_by_liner   display_by_methodr   display_about_methodr   display_hotpathr   write_to_flamer   write_to_jsonr   write_to_chrome	Exceptionr*   )r]   formatdatakwargsr   s        r   r   r     s   |	z######_
4<A
*+++&&&b!!!!	>*	*	*$####	>-	-	-T2000000	>)	)	)b++F++++	>,	,	,tR**6****	>&	&	&dB	>(	(	(b++F++++0111n)>+@AAA

&T\):)::;;;
69NNOOOOO BAr   c                    t                               | j                  }|                    dd            |                    ddz             |                    ddz             |D ]}|j        }d|                                |j        |j        fz  }|                    d	|	                                |
                                |                                |fz             d
S )zsPrint the profiler data with each sample line represented
    as one row in a table.  Sorted by self-time per line.Tc                 *    |                                  S r6   r   xs    r   <lambda>z!display_by_line.<locals>.<lambda>  s    1==?? r   reversekey   %5.5s %10.10s   %7.7s  %-8.8s
s   %  s
   cumulatives   selfr      %5.5s  %9.9s  %8.8s  %-8.8s
s   time   secondsr  s   names   %s:%d:%s   %6.2f %9.2f %9.2f  %s
N)r   r   r/   sortr   r   rc   rD   rE   r   r   r   )r   r]   r   statr   	sitelabels         r   r   r     s      ..E	JJt!:!:J;;;HH*
/	0   HH(
4	5  
  
 
y4==??DK"OO	
&  ""!!##  ""		
 	
 	
 	

 
r   c           	         |                     ddz             |                     ddz             t                              | j                  }t	          t
                    }|D ]D}||j                                        dz   |j        j        z            	                    |           Eg }|
                                D ]o\  }}d}d}	d}
|D ]G}||                                z  }|	|                                z  }	|
|                                z  }
H|	                    |||	|
|f           p|                    dd 	           |D ]}|d
         dk     r|                     d|d
         |d         |d         |d         fz             |d                             dd 	           |d         D ]}|                                dk    r|j                            d          }t!          |t"                    st%          j        |          }|                                |                                |j        j        |f}|                     d|z             dS )zPrint the profiler data with each sample function represented
    as one row in a table.  Important lines within that function are
    output as nested rows.  Sorted by self-time per line.r  r	  r
  r     :r   Tc                     | d         S )Nr   r@   r  s    r   r  z#display_by_method.<locals>.<lambda>N  s
    !A$ r   r  rY   皙?r  r   r   r   c                 *    |                                  S r6   r  )r^   s    r   r  z#display_by_method.<locals>.<lambda>]  s    Q]]__ r      s   %33.0f%% %6.2f   line %d: %s
N)r   r   r   r/   defaultdictlistr   rc   rE   rp   r   r   r   r   r  r`   rH   rI   r   bytestrrD   )r   r]   r   groupedr  functiondatafname	sitestatstotal_cum_sectotal_self_sectotal_percentrE   rF   	stattuples                 r   r   r   +  s    HH*
/	0   HH(
4	5  
   ..E$G O O	""$$t+di.@@AHHNNNN L#MMOO 
 
y 	0 	0DT..000Md..000NT--///MMM>=)L	
 	
 	
 	

 d777  H HA;
&		
 	
 	
 	+D+DEEEQK 	H 	HD!!A%%,,R00!&%00 6%-f55F $$&&$$&&I$		 :YFGGG	HH Hr   c                    t          d          d dv r                    d          \  d}i }i }| j        D ]}t          |j                  D ]\  }}	|	j        k    rzr|	                                k    r`|dz  }|t          |j                  dz
  k    r(|j        |dz            }
|
|v r||
         dz   ||
<   nd||
<   |	|v r||	         dz   ||	<   d||	<   d |                                D             }|	                    dd            |D ]\  }
}|
                    d	||z  d
z  t          j        |
                                          t          j        |
j                  |
j        t          j        |
                    d                    fz             t                               | j                  }fd|D             }d}d}d}d}|D ]^}||                                z  }||                                z  }||                                z  }||                                z  }_|
                    dt          j        pd          t          j                  ||||fz             d |                                D             }|	                    dd            |D ]P\  }}|
                    d||z  d
z  |j        t          j        |                    d                    fz             Qd S )NzInvalid functionr  r   r   c                     g | ]	\  }}||f
S r@   r@   )r   parentcounts      r   r   z(display_about_method.<locals>.<listcomp>  s     DDD=65DDDr   Tc                     | d         S r   r@   r  s    r   r  z&display_about_method.<locals>.<lambda>  s
    QqT r   r  s   %6.2f%%   %s:%s   line %s: %s
r   2   c                 r    g | ]3}|j         j        k    r!r|j                                         k    1|4S r@   )r   rE   rc   )r   r   rc   rE   s     r   r   z(display_about_method.<locals>.<listcomp>  sS       6?h&& 'V__..(:: 	
 ;::r   sA   
    %s:%s    Total: %0.2fs (%0.2f%%)    Self: %0.2fs (%0.2f%%)

s   ___c                     g | ]	\  }}||f
S r@   r@   )r   childr%  s      r   r   z(display_about_method.<locals>.<listcomp>  s     DDD<5%DDDr   c                     | d         S r   r@   r  s    r   r  z&display_about_method.<locals>.<lambda>  s
    ad r   s           %6.2f%%   line %s: %s
)r   r   r/   rZ   rl   rE   rc   r8   r   r  r   r   fsencoderq   rD   r`   r   r   r   r   r   r   )r   r]   rE   r   relevant_samplesparentschildrenr   r^   r   r$  r%  r   r  r  total_self_percenttotal_cum_percentr  r*  rc   s     `                @r   r   r   o  s   *+++Hx%^^D11(GH, ' ' .. 	' 	'GAt}(( ) $8 ; ; A% FL))A---#\!a%0F((*1&/A*=*+8##%-d^a%7HTNN%&HTN	'" EDGMMOODDDGLL>>L222  

 


.((3.!&//"3"344!&/22!&"2"22"6"677		
 		
 		
 		
   ..E      E MN 1 1**,,,$**,,,d..000T..000HHOh0&11h''
	

 
 
 ED8>>3C3CDDDHMM$NNM333  
 
u
.((3.!%//""5"566	
 	
 	
 	

 
r   r  c                 V  	  G fdd           d           | j         d         j        }| j         D ]5}                    |j        d d d         |j        |z
             |j        }6|                    dd          		fdj        dk    r dd           d S d S )	Nc                        e Zd Zd Z fdZdS ) display_hotpath.<locals>.HotNodec                 0    || _         d| _        i | _        d S r   )r   r%  r/  r   s     r   r%   z)display_hotpath.<locals>.HotNode.__init__  s    DIDJDMMMr   c                 (   | xj         |z  c_         |d         }| j                            |          }|s |          }|| j        |<   t          |          dk    rd}|t          |          k     rZ||                                         t
          v r9|dz  }|t          |          k     r!||                                         t
          v 9|t          |          k     r |                    ||d          |           d S d S |xj         |z  c_         d S r1   )r%  r/  rV   r8   rf   skipsadd)r#   rl   rm   r   r*  r^   HotNodes         r   r8  z$display_hotpath.<locals>.HotNode.add  s   JJ$JJ8DM%%d++E ,&+d#5zzA~~#e**nnq):):)<)<)E)EFA #e**nnq):):)<)<)E)Es5zz>>IIeABBi..... "> t#r   N)r<   r=   r>   r%   r8  )r9  s   r   r9  r4    s=        	 	 	
	$ 	$ 	$ 	$ 	$ 	$ 	$r   r9  r   showtimeTc                 x   | j         }fd| j                                        D             }|r|dz  dz
  }|                                dz                       d          }|j        }d                    |          |rdndz   d	z   r
d
| j        z  ndz   dz   }|| j        j        z  dz  ||fz  }	t          ddt          |	          z
            }
d}|
dk    rd}d}||d	                    |
          |j
        |j
        ndd                    t          ddt          t          |j
                            z
                      |                    d          fz  }|	|z   }t          d | j                                        D                       }| j        |z
  dj        z  k    r	d|z   dz   }n| j        |z
  dk    rd|z   dz   }                    |dz              |}t          |          dk    s|r|dz  }|                    dd            |D ] } ||t          |          dk               !d S )Nc                 :    g | ]}|j         j         z  k    |S r@   r%  )r   climitroots     r   r   z3display_hotpath.<locals>._write.<locals>.<listcomp>  s3     
 
 
UTZ=O1P1PA1P1P1Pr   r   r   r     r      \   |s    %4.1f%%s    %5.2fss     %s %sr   r   7   s   , s   %s%s %d: %s%ss   liner:  r      c                     g | ]	}|j         
S r@   r>  )r   r?  s     r   r   z3display_hotpath.<locals>._write.<locals>.<listcomp>  s    "K"K"Kq17"K"K"Kr   g?s   [91ms   [0ms   [90m   
Tc                     | j         S r6   r>  r  s    r   r  z1display_hotpath.<locals>._write.<locals>.<lambda>  s     r   r  )r   r/  r   rc   ljustrE   r%  maxr8   rjustrD   strr`   sumr   r  )nodedepthmultiple_siblingsr   visiblechildrenindentrc   rE   listpattern
liststringspacing_lenprefixcodepattern
codestringfinalstringchildrensamplesnewdepthr*  _writer]   r@  rA  r;  s                     r   r]  zdisplay_hotpath.<locals>._write  s   y
 
 
 
 
}++--
 
 
  )	*QY]F$.55b99H}H 		&!!-75549 /7?:
**CA 	  %
TZ'#-( J ac*oo!566KFa*K$k**#{6B		#aST[)9)9%:%:!:;;<<r""( J %z1K!"K"KDM4H4H4J4J"K"K"KLLOzO+sTZ/?@@)K7*Do-22)K7*DHH[5()))!##'8#MHT/@/@AAA$ 	> 	>EF5(C$8$81$<====	> 	>r   F)r/   rm   r8  rl   rV   r%  )
r   r]   r@  r   lasttimer   r9  r]  rA  r;  s
    ``   @@@@r   r   r     s   $ $ $ $ $ $ $ $ $ $2 74==D|A#H,  ddd#V[8%;<<<;zz*d++H6> 6> 6> 6> 6> 6> 6> 6> 6>p zA~~tQ ~r   c                    |t           j        d         dz   }t          j                            |          s/|                    d|z             |                    d           d S i }| j        D ]T}d |j        D             }|                                 d	                    |          }||v r||         dz   ||<   Od||<   Ut          j                    \  }	}
t          |
d          5 }|                                D ]\  }}|                    d	||fz              	 d d d            n# 1 swxY w Y   |d
}t          j        d|
|fz             |                    d|z             d S )Ns   HOMEs   /flamegraph.pls   error: missing %s
s8   get it here: https://github.com/brendangregg/FlameGraph
c                     g | ]	}|j         
S r@   )rE   r   s     r   r   z"write_to_flame.<locals>.<listcomp>-  s    222222r      ;r   r   s   %s %d
s   ~/flamegraph.svgs   perl ~/flamegraph.pl %s > %ss   Written to %s
)r   r   r   rC   existsr   r/   rl   r  r   r   mkstempr   r   system)r   r]   
scriptpath
outputfiler   r   r   r   r_   fdrC   r   r%  s                r   r   r   #  s   %g.1BB
7>>*%% 
'*4555
MNNNE,  22V\222yy5==+/E$KKE$KK!!HB	dE		 3d ;;== 	3 	3KD%JJzT5M12222	33 3 3 3 3 3 3 3 3 3 3 3 3 3 3 (
I-z0BBCCCHH*,-----s   *5D,,D03D0c                 F   | t           v rt           |          S t          j                            t          j        d          d         }|gt          j        z   D ]?}|t          j        z   }|                     |          r| t          |          d         }  n@| t           | <   | S )zAttempt to make the path to a Python module easier to read by
    removing whatever part of the Python search path it was found
    on.r   r   N)

_pathcacher   __file__rsplitr   sepr   rC   
startswithr8   )rC   hgpathprW  s       r   simplifypathrp  E  s    
 z$%%bfa003FX   RV??6"" 	F&DE	 JtKr   c           	         g }| j         D ]u}g }|j        D ]M}|                    t          j        |j                  |j        t          j        |j                  f           N|                    |j        |f           vt          j
        |          } t          | t                    s|                     d          } |                    |            d S )Nutf-8)r/   rl   rp   r   sysstrrC   rD   rE   rm   jsondumpsrH   rI   encoder   )r   r]   r/   r   rl   rw   s         r   r   r   V  s    G, - -\ 	 	ELLOEJ//LOEN33    	U+,,,,:gDdE"" ${{7##HHTNNNNNr   {Gzt?+?c                    g t          j                    t          j                    i g fddt                      | j        d         j        | j        d         j        z
  }|z  t          |z            f	d}| j        D ]Ot          d j        D                       }t          j        |          }|k    r<rR|rPd         |d         k    r>                                 |                                 r|rd         |d         k    >r |             t          |          D ]}
                    j        t                    f           
                    |           |\  }	}
 t                              }                    t          d|
|	j        dz  |d	                     t          j        |          Qr |             fd
t                    D             }t          j        d t                    D                       }t!          j        t          ||          d          } t%          | t&                    s|                     d          } |                    |            |                    d           d S )Nc                 $   | sd S | v r|          S  | dd                    }t                    }|| <                       t          | d         d         d| d         z                       |d                             |           |S )Nr   r   z%s %s)categoryr   r:  )r$  )r8   rp   dictupdate)rl   r$  myidid2stackstack2idstackids      r   r  z write_to_chrome.<locals>.stackidy  s     	FHE?"qrr##8}}eAhqk%(8JKKKLLLRLv...r   r)   r:  r   c            
      |  	  t          
                    } 
                                \  }}	                                \  }}j        |z
  }|cxk    rk    rHn nEt          |z   j                  }                    t          d||| |dz  d                     d S                     |           d S )NE    .Ar   )phr   catsftspid)tuplepopleftrm   rK  rp   r|  r8  )oldsidoldcatoldfuncoldtimeoldidxduration
sampletime	blacklistclamplastseen	laststackmaxthresholdminthresholdr   r/   r  s          r   poplastz write_to_chrome.<locals>.poplast  s    y))**#++--"**,,;(83333|33333Wu_fk::JNN !C'  	 	 	 	 	 MM&!!!!!r   c              3      K   | ]M}d t          t          j        |j                            |j        fz  t          j        |j                  fV  NdS )z%s:%dN)rp  r   rs  rC   rD   rE   )r   rw   s     r   	<genexpr>z"write_to_chrome.<locals>.<genexpr>  sp         	 #HOEJ$?$?@@%,OPOEN33     r   Br  )r  r   r  r  r  r  c                 "    g | ]\  }}|v	|S r@   r@   )r   idxr   r  s      r   r   z#write_to_chrome.<locals>.<listcomp>  s.       398L8L8L8L8Lr   c              3   >   K   | ]\  }}t          |          |fV  d S r6   )rM  )r   rT   rU   s      r   r  z"write_to_chrome.<locals>.<genexpr>  sA       % %AQ% % % % % %r   )traceEventsstackFramesr   )rS  rr  rH  )collectionsdequer   r/   rm   rK  r  rl   popreversed
appendleftr8   rp   r|  rZ   OrderedDictrt  ru  rH   rI   rv  r   )r   r]   r  r  	totaltimer  rl   qstackr   rC   r   sideventsframesr  r  r  r  r  r   r/   r  r  s     ``          @@@@@@@@@r   r   r   n  s}   G!##I ""H
 HH      & E IR %Q(<<I|+Ly</77L" " " " " " " " " " " " "0 , "- "-  $\  	
 	
 "5)) 	F 	y}r
'B'BMMOOOJJLLL  	F 	y}r
'B'B  	GIII  	&!! 	 	Ac'll ;<<<  ###JD$'%	**++CNN{S(  	 	 	 	  %e,,		
 			     "+G"4"4  F $ % %"+H"5"5% % %  F :dv6BBB1MMMDdE"" ${{7##HHTNNNHHUOOOOOr   c                  $    t          d           d S )Na  
The statprof command line allows you to inspect the last profile's results in
the following forms:

usage:
    hotpath [-l --limit percent]
        Shows a graph of calls with the percent of time each takes.
        Red calls take over 10%% of the total time themselves.
    lines
        Shows the actual sampled lines.
    functions
        Shows the samples grouped by function.
    function [filename:]functionname
        Shows the callers and callees of a particular function.
    flame [-s --script-path] [-o --output-file path]
        Writes out a flamegraph to output-file (defaults to ~/flamegraph.svg)
        Requires that ~/flamegraph.pl exist.
        (Specify alternate script path with --script-path.))printr@   r   r   
printusager    s#    		?    r   c                    | t           j        } t          |           dk    rt                       dS i }d}d |d<   | d         dk    rt          j        |d<   n| d         dk    rt          j        |d<   nq| d         dk    rt          j        |d<   nU| d         d	k    rt          j        |d<   | d         |d<   d
}n,| d         dk    rt          j	        |d<   nt                       dS 	 t          j        t           j        |d          dg d          \  }}n:# t          j        $ r(}t          |           t                       Y d }~dS d }~ww xY wd|d<   d }|D ]X\  }}|dv rt          |          |d<   |dv r|}#|dv r||d<   -|dv r||d<   7|dv rt                        dS J d|z              |st          d           dS t!          |           t#          di t          j        |           dS )Nr   r   r   s   functionhotpaths   formatr   	functionsrE   rY   flames	   hl:f:o:p:)s   helps   limit=s   file=s   output-file=s   script-path=r  s   limit)z-lz--limit)z-fz--file)z-oz--output-files
   outputfile)z-pz--script-paths
   scriptpath)z-hhelpFzunhandled option %szmust specify --file to load)rC   r@   )r   argvr8   r  r   r   r   r   r   r   r   getoptbgetopterrorr  r   r   r   	strkwargs)	r  displayargsoptstartoptsr   msgrC   or   s	            r   mainr    s}   |x
4yyA~~qKH#KAw)!/!7I	aG		!/!6I	aK		!/!8I	aJ		!/!;I#'7K 	aG		!/!:Iq	%HXYYLLL
 

dd
 <   c


qqqqq
 !KD 4 45!!!$)%LLK!!"""DD)))).K&&)))).K&&.  LLL113/!3333 +,,,q4..h --...1s   %-D E
"EE
__main__)r   r   r6   )NrY   N)r  )NN)rw  rx  )4__doc__r  
contextlibr  r   rt  r   r{   r   r   rm   r   r    r   r  contextmanager__all__r7  r   r   rz   rB   rj   r   Eventr   r   r   r   r   r   r   r   r    r   r   r   r   r   r   r   r   r   ri  rp  r   r   r  r  r<   exitr@   r   r   <module>r     s  0N Nb            				  



                  
 %*
?
?
?	 	 	*+ + +* * * * * * * *Z 	7: 7: 7: 7: 7: 7: 7: 7:t# # # # # # # #8	$ 	$ 	$ Y_
  (# # # ! ! ! !4  *
@ 
@ 
@2 2 2&      (+ (+ (+ (+ (+ (+ (+ (+V       !P !P !P !PH
 
 
:AH AH AHHT
 T
 T
 T
nZ Z Z Zz. . . .> 
  "  0u u u up  .A A A AH zCHTTVV r   