3 ^Vc@sdZddlZddlZddlZddlZddlmZdddgZGdddZdd dZ dd dZ Gd ddZ d dZ e dkre dS)z Class for profiling Python code.N) OptionParserrunrunctxProfilec@s0eZdZdZddZddZddZdd Zd S) _UtilszSupport class for utility functions which are shared by profile.py and cProfile.py modules. Not supposed to be used directly. cCs ||_dSN)profiler)selfrr /usr/lib64/python3.6/profile.py__init__1z_Utils.__init__cCsF|j}z(y|j|Wntk r,YnXWd|j|||XdSr)rr SystemExit_show)r statementfilenamesortprofr r r r4s  z _Utils.runcCsJ|j}z,y|j|||Wntk r0YnXWd|j|||XdSr)rrr r)rrglobalslocalsrrrr r r r=s  z _Utils.runctxcCs"|dk r|j|n |j|dSr) dump_stats print_stats)rrrrr r r rFs z _Utils._showN)__name__ __module__ __qualname____doc__r rrrr r r r r+s   rcCsttj|||S)aRun statement under profiler optionally saving results in filename This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this routine attempts to "exec" its first argument and gather profiling statistics from the execution. If no file name is present, then this function automatically prints a simple profiling report, sorted by the standard name string (file/line/function-name) that is presented in each line. )rrr)rrrr r r rRs cCsttj|||||S)zRun statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run )rrr)rrrrrr r r r_sc@seZdZdZdZd4ddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ e e e e e e dZddZGdddZGdddZddZdd Zd6d"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd7d0d1Zd2d3ZdS)8raProfiler class. self.cur is always a tuple. Each such tuple corresponds to a stack frame that is currently active (self.cur[-2]). The following are the definitions of its members. We use this external "parallel stack" to avoid contaminating the program that we are profiling. (old profiler used to write into the frames local dictionary!!) Derived classes can change the definition of some entries, as long as they leave [-2:] intact (frame and previous tuple). In case an internal error is detected, the -3 element is used as the function name. [ 0] = Time that needs to be charged to the parent frame's function. It is used so that a function call will not have to access the timing data for the parent frame. [ 1] = Total time spent in this frame's function, excluding time in subfunctions (this latter is tallied in cur[2]). [ 2] = Total time spent in subfunctions, excluding time executing the frame's function (this latter is tallied in cur[1]). [-3] = Name of the function that corresponds to this frame. [-2] = Actual frame that we correspond to (used to sync exception handling). [-1] = Our parent 6-tuple (corresponds to frame.f_back). Timing data for each function is stored as a 5-tuple in the dictionary self.timings[]. The index is always the name stored in self.cur[-3]. The following are the definitions of the members: [0] = The number of times this function was called, not counting direct or indirect recursion, [1] = Number of times this function appears on the stack, minus one [2] = Total time spent internal to this function [3] = Cumulative time that this function was present on the stack. In non-recursive functions, this is the total execution time from start to finish of each invocation of a function, including time spent in all subfunctions. [4] = A dictionary indicating for each function name, the number of times it was called by us. rNc Csi|_d|_d|_d|_|dkr&|j}||_|sHtj|_|_|j |_ nl||_|j}y t |}Wn"t k r||_|j |_ Yn0X|dkr|j |_ n|j|_ |tfdd}||_|j|_|jddS)NcSs ||Srr )timersumr r r get_time_timerr z(Profile.__init__..get_time_timerr)timingscurcmd c_func_namebiastimeZ process_timerget_timetrace_dispatch_i dispatcherlen TypeErrortrace_dispatchtrace_dispatch_lrt simulate_call)rrr%r.Zlengthr r r r r s0    zProfile.__init__cCs|j}|}|d|d|j|j}|dkr8|j|_|j||||rd|}|d|d|_n|}|d|d||_dS)Nrrc_callrr.r%rr$dispatch)rframeeventargrr.Zrr r r r,szProfile.trace_dispatchcCT|j}||j|j}|dkr(|j|_|j||||rD||_n |||_dSNr0r1rr3r4r5rr.r r r r( zProfile.trace_dispatch_icCs`|j}|d|j|j}|dkr,|j|_|j||||rL|d|_n|d||_dS)NgN@r0r1r8r r r trace_dispatch_macszProfile.trace_dispatch_maccCr6r7)r'r.r%rr$r2)rr3r4r5r'r.r r r r-r9zProfile.trace_dispatch_lc CsD|j\}}}}}}||k r*|r*|j||S|||||||f|_dSNr)r"trace_dispatch_return) rr3r.rptritretrfnrframercurr r r trace_dispatch_exceptions   z Profile.trace_dispatch_exceptioncCs|jr|j|jdk r|j\}}}}}}t|tjs|j|jksXtd|||j||jf|j|d|jdks|j|jdkstd|jdf|j} | j| j | j f} |dd| ||jf|_|j } | | kr| | \} } }}}| | d|||f| | <nddddif| | <dS) NrzBad callrrrE) r"f_backZ isinstancer fake_frameAssertionErrorr<f_code co_filenameco_firstlinenoco_namer!)rr3r.r=r>r?r@rArBZfcodefnr!ccnsttctcallersr r r trace_dispatch_calls&    zProfile.trace_dispatch_callc Csndd|jf}|dd|||jf|_|j}||krX||\}}}}} ||d||| f||<nddddif||<dS)Nrrr)r$r"r!) rr3r.rNr!rOrPrQrRrSr r r trace_dispatch_c_calls zProfile.trace_dispatch_c_callcCs||jdk rB||jdjks0td|jdf|j|jd d|j\}}}}}}||}||}|\} } } } } }| | || || | |f|_|j}||\}}}}}|s||}|d}| |kr|| d|| <nd|| <||d||||f||<dS) Nrz Bad returnrDrrrErErFrE)r"rGrIr<r!)rr3r.r=r>r?r@rBZ frame_totalZpptZpitZpetZpfnpframeZpcurr!rOrPrQrRrSr r r r<#s$"zProfile.trace_dispatch_return)callZ exceptionreturnr0Z c_exceptionZc_returncCs"|jdrdS||_|j|dS)Nr)r"r#r/)rr#r r r set_cmdYs zProfile.set_cmdc@seZdZddZddZdS)zProfile.fake_codecCs||_||_||_d|_dSNr)rKco_linerMrL)rrlinenamer r r r _szProfile.fake_code.__init__cCst|j|j|jfSr)reprrKr\rMrr r r __repr__er zProfile.fake_code.__repr__N)rrrr rar r r r fake_code^srbc@seZdZddZdS)zProfile.fake_framecCs||_||_dSr)rJrG)rcodeZpriorr r r r iszProfile.fake_frame.__init__N)rrrr r r r r rHhsrHcCsF|jdd|}|jr |jd}nd}|j||}|jd||ddS)NZprofilerrrWrE)rbr"rHr2)rr^rcrVr3r r r r/ms   zProfile.simulate_callcCsN|j}||j}x*|jdr<|jd||jd|d}qW|||_dS)NrrXrrrYrE)r'r.r"r2)rr'r.r r r simulate_cmd_completeys   zProfile.simulate_cmd_completercCs$ddl}|j|jj|jdSr[)pstatsZStatsZ strip_dirsZ sort_statsr)rrrer r r rzProfile.print_statsc Cs0t|d}|jtj|j|WdQRXdS)NZwb)open create_statsmarshalZdumpstats)rZfilefr r r rs zProfile.dump_statscCs|j|jdSr)rdsnapshot_statsr`r r r rhrfzProfile.create_statsc Csfi|_xZ|jjD]L\}\}}}}}|j}d}x|jD] }||7}q:W|||||f|j|<qWdSr[)rjr!itemsZcopyZvalues) rfuncrOrPrQrRrSZncZcallcntr r r rls zProfile.snapshot_statscCsddl}|j}|j|||Sr[)__main__Z__dict__r)rr#roZdictr r r rsz Profile.runc Cs8|j|tj|jzt|||WdtjdX|Sr)rZsys setprofiler)exec)rr#rrr r r rs    zProfile.runctxc Os6|jt|tj|jz |||StjdXdSr)rZr_rprqr))rrnargsZkwr r r runcalls   zProfile.runcallc Cs8|jtk rtd|j}d|_z |j||S||_XdS)Nz&Subclasses must override .calibrate().r)Z __class__rr+r%_calibrate_inner)rmverboseZ saved_biasr r r calibrates  zProfile.calibratecCs$|j}dd}|fdd}|||}|||}||}|rLtd|t} |}| jdtt|}||} |rtd| d} d} x>| jjD]0\\} }}\}}}}}|dkr| |7} | |7} qW|rtd | td | | |d krtd| | |d| }|r td||S)NcSsxt|D]}d}q WdSr;Zrange)ZniZxr r r f1z$Profile._calibrate_inner..f1cSsxt|D] }|dq WdS)Nidry)rvr{rzr r r rkr|z#Profile._calibrate_inner..fz elapsed time without profiling =zf(m)zelapsed time with profiling =grkr{z!'CPU seconds' profiler reported =ztotal # calls =rz internal error: total calls = %dg@z+mean stopwatch overhead per profile event =)rkr{) r'Zprintrrrrr!rmZ ValueError)rrvrwr'r{rkZt0Zt1Zelapsed_noprofileZpZelapsed_profileZ total_callsZ reported_timerr]ZfuncnamerOrPrQrRrSZmeanr r r rusB   "     zProfile._calibrate_inner)NNrY)rY)r)rrrrr%r r,r(r:r-rCrTrUr<r2rZrbrHr/rdrrrhrlrrrtrxrur r r r rhs>% ' '      1 c Csd}t|d}d|_|jdddddd|jd d d d ddtjd ds\|jtjd|j\}}|tjdd<t|dkr|d}tj j dt j j |t |d}t|j|d}WdQRX|dddd}t||d|j|jn|j|S)Nz?profile.py [-o output_file_path] [-s sort] scriptfile [arg] ...)usageFz-oz --outfileoutfilezSave stats to )ZdestZhelpZdefaultz-sz--sortrz?Sort order when printing to stdout, based on pstats.Stats classrrrZrbrrro)Z__file__rZ __package__Z __cached__rY)rZallow_interspersed_argsZ add_optionrpZargvZ print_usageZexitZ parse_argsr*ZpathZinsertosZdirnamergZcompileZreadrr~r)r}ZparserZoptionsrsZprognameZfprcZglobsr r r main*s2        rrorYNrYrYr)rrprr&riZoptparserZ__all__rrrrrrr r r r Z s   ' E"