The Python ProfilersPython探查器¶
Source code: Lib/profile.py and Lib/pstats.py
Introduction to the profilers轮廓仪简介¶
cProfile
and profile
provide deterministic profiling of Python programs. cProfile
和profile
提供了Python程序的确定性评测。A profile is a set of statistics that describes how often and for how long various parts of the program executed. 概要文件是一组统计信息,描述程序各个部分执行的频率和时间。These statistics can be formatted into reports via the 这些统计数据可以通过pstats
module.pstats
模块格式化为报告。
The Python standard library provides two different implementations of the same profiling interface:Python标准库提供了相同评测接口的两种不同实现:
cProfile
is recommended for most users; it’s a C extension with reasonable overhead that makes it suitable for profiling long-running programs.建议大多数用户使用;它是一个具有合理开销的C扩展,适合于分析长时间运行的程序。Based on基于lsprof
, contributed by Brett Rosen and Ted Czotter.lsprof
,由Brett Rosen和Ted Czotter提供。profile
, a pure Python module whose interface is imitated by,是一个纯Python模块,其接口由cProfile
, but which adds significant overhead to profiled programs.cProfile
模仿,但这会给评测程序增加大量开销。If you’re trying to extend the profiler in some way, the task might be easier with this module.如果您试图以某种方式扩展探查器,则使用此模块可能会更轻松。Originally designed and written by Jim Roskind.最初由吉姆·罗斯金设计和撰写。
Note
The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes (for that, there is 探查器模块旨在为给定程序提供执行概要文件,而不是用于基准测试(为此,有timeit
for reasonably accurate results). timeit
获得合理准确的结果)。This particularly applies to benchmarking Python code against C code: the profilers introduce overhead for Python code, but not for C-level functions, and so the C code would seem faster than any Python one.这尤其适用于将Python代码与C代码进行比较:分析器为Python代码引入了开销,但不为C级函数引入开销,因此C代码似乎比任何Python代码都快。
Instant User’s Manual即时用户手册¶
This section is provided for users that “don’t want to read the manual.” 本节为“不想阅读手册”的用户提供It provides a very brief overview, and allows a user to rapidly perform profiling on an existing application.它提供了一个非常简短的概述,并允许用户在现有应用程序上快速执行概要分析。
To profile a function that takes a single argument, you can do:要评测采用单个参数的函数,可以执行以下操作:
import cProfile
import re
cProfile.run('re.compile("foo|bar")')
(Use (如果系统上没有profile
instead of cProfile
if the latter is not available on your system.)cProfile
,请使用cProfile
而不是cProfile
。)
The above action would run 上述操作将运行re.compile()
and print profile results like the following:re.compile()
并打印配置文件结果,如下所示:
197 function calls (192 primitive calls) in 0.002 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.001 0.001 <string>:1(<module>)
1 0.000 0.000 0.001 0.001 re.py:212(compile)
1 0.000 0.000 0.001 0.001 re.py:268(_compile)
1 0.000 0.000 0.000 0.000 sre_compile.py:172(_compile_charset)
1 0.000 0.000 0.000 0.000 sre_compile.py:201(_optimize_charset)
4 0.000 0.000 0.000 0.000 sre_compile.py:25(_identityfunction)
3/1 0.000 0.000 0.000 0.000 sre_compile.py:33(_compile)
The first line indicates that 197 calls were monitored. 第一行表示监控了197个呼叫。Of those calls, 192 were primitive, meaning that the call was not induced via recursion. 在这些调用中,192个是原始的,这意味着调用不是通过递归引起的。The next line: 下一行:Ordered by: standard name
, indicates that the text string in the far right column was used to sort the output. Ordered by: standard name
,表示最右侧列中的文本字符串用于对输出进行排序。The column headings include:列标题包括:
- ncalls
for the number of calls.电话号码。- tottime
for the total time spent in the given function (and excluding time made in calls to sub-functions)在给定函数中花费的总时间(不包括调用子函数的时间)- percall
is the quotient of是tottime
divided byncalls
tottime
除以ncalls
的商- cumtime
is the cumulative time spent in this and all subfunctions (from invocation till exit).是此子函数和所有子函数(从调用到退出)中花费的累积时间。This figure is accurate even for recursive functions.这个数字即使对于递归函数也是准确的。- percall
is the quotient of是cumtime
divided by primitive callscumtime
除以原始调用的商- filename:lineno(function)
provides the respective data of each function提供每个函数的相应数据
When there are two numbers in the first column (for example 当第一列中有两个数字(例如3/1
), it means that the function recursed. 3/1
)时,表示函数递归。The second value is the number of primitive calls and the former is the total number of calls. 第二个值是原语调用的数量,前者是调用的总数。Note that when the function does not recurse, these two values are the same, and only the single figure is printed.注意,当函数不递归时,这两个值是相同的,并且只打印一个数字。
Instead of printing the output at the end of the profile run, you can save the results to a file by specifying a filename to the 您可以通过为run()
function:run()
函数指定文件名来将结果保存到文件中,而不是在概要文件运行结束时打印输出:
import cProfile
import re
cProfile.run('re.compile("foo|bar")', 'restats')
The pstats.Stats
class reads profile results from a file and formats them in various ways.pstats.Stats
类从文件中读取配置文件结果,并以各种方式对其进行格式化。
The files 文件cProfile
and profile
can also be invoked as a script to profile another script. cProfile
和profile
也可以作为脚本调用,以评测另一个脚本。For example:例如:
python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)
-o
writes the profile results to a file instead of to stdout将配置文件结果写入文件而不是stdout
-s
specifies one of the 指定要对输出进行排序的sort_stats()
sort values to sort the output by. sort_stats()
排序值之一。This only applies when 这仅适用于未提供-o
is not supplied.-o
的情况。
-m
specifies that a module is being profiled instead of a script.指定正在分析模块而不是脚本。
The pstats
module’s Stats
class has a variety of methods for manipulating and printing the data saved into a profile results file:pstats
模块的Stats
类有多种方法来处理和打印保存到配置文件结果文件中的数据:
import pstats
from pstats import SortKey
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()
The strip_dirs()
method removed the extraneous path from all the module names. strip_dirs()
方法从所有模块名称中删除了多余的路径。The sort_stats()
method sorted all the entries according to the standard module/line/name string that is printed. sort_stats()
方法根据打印的标准模块/行/名称字符串对所有条目进行排序。The print_stats()
method printed out all the statistics. print_stats()
方法打印出所有统计信息。You might try the following sort calls:您可以尝试以下排序调用:
p.sort_stats(SortKey.NAME)
p.print_stats()
The first call will actually sort the list by function name, and the second call will print out the statistics. 第一个调用实际上将按函数名对列表进行排序,第二个调用将打印统计信息。The following are some interesting calls to experiment with:以下是一些值得尝试的有趣调用:
p.sort_stats(SortKey.CUMULATIVE).print_stats(10)
This sorts the profile by cumulative time in a function, and then only prints the ten most significant lines. 这将按函数中的累积时间对配置文件进行排序,然后只打印十条最重要的行。If you want to understand what algorithms are taking time, the above line is what you would use.如果你想了解什么算法需要时间,上面这一行就是你要使用的。
If you were looking to see what functions were looping a lot, and taking a lot of time, you would do:如果您想了解哪些函数循环频繁,并且花费了大量时间,您可以这样做:
p.sort_stats(SortKey.TIME).print_stats(10)
to sort according to time spent within each function, and then print the statistics for the top ten functions.根据每个函数中花费的时间进行排序,然后打印前十个函数的统计信息。
You might also try:您也可以尝试:
p.sort_stats(SortKey.FILENAME).print_stats('__init__')
This will sort all the statistics by file name, and then print out statistics for only the class init methods (since they are spelled with 这将按文件名对所有统计信息进行排序,然后只打印出类init方法的统计信息(因为它们的拼写是__init__
in them). __init__
)。As one final example, you could try:作为最后一个示例,您可以尝试:
p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init')
This line sorts statistics with a primary key of time, and a secondary key of cumulative time, and then prints out some of the statistics. 这行使用时间主键和累积时间主键对统计信息进行排序,然后打印出一些统计信息。To be specific, the list is first culled down to 50% (re: 具体来说,首先将列表缩小到原始大小的50%(re:.5
) of its original size, then only lines containing init
are maintained, and that sub-sub-list is printed..5
),然后只保留包含init
的行,然后打印该子列表。
If you wondered what functions called the above functions, you could now (如果您想知道哪些函数称为上述函数,现在可以(p
is still sorted according to the last criteria) do:p
仍然根据最后的标准排序):
p.print_callers(.5, 'init')
and you would get a list of callers for each of the listed functions.您将获得每个列出的函数的调用方列表。
If you want more functionality, you’re going to have to read the manual, or guess what the following functions do:如果您想要更多功能,您必须阅读手册,或者猜测以下功能的作用:
p.print_callees()
p.add('restats')
Invoked as a script, the pstats
module is a statistics browser for reading and examining profile dumps. pstats
模块作为脚本调用,是用于读取和检查概要文件转储的统计浏览器。It has a simple line-oriented interface (implemented using 它有一个简单的面向行的界面(使用cmd
) and interactive help.cmd
实现)和交互式帮助。
profile
and cProfile
Module Reference¶
Both the profile
and cProfile
modules provide the following functions:profile
和cProfile
模块都提供以下功能:
-
profile.
run
(command, filename=None, sort=- 1)¶ This function takes a single argument that can be passed to the此函数接受一个可以传递给exec()
function, and an optional file name.exec()
函数的参数和一个可选的文件名。In all cases this routine executes:在所有情况下,该例程执行:exec(command, __main__.__dict__, __main__.__dict__)
and gathers profiling statistics from the execution.并从执行中收集分析统计信息。If no file name is present, then this function automatically creates a如果没有文件名,则此函数会自动创建Stats
instance and prints a simple profiling report.Stats
实例并打印一个简单的分析报告。If the sort value is specified, it is passed to this如果指定了排序值,它将传递给这个Stats
instance to control how the results are sorted.Stats
实例,以控制结果的排序方式。
-
profile.
runctx
(command, globals, locals, filename=None, sort=- 1)¶ This function is similar to此函数类似于run()
, with added arguments to supply the globals and locals dictionaries for the command string.run()
,添加了参数为command字符串提供全局和局部字典。This routine executes:此例程执行:exec(command, globals, locals)
and gathers profiling statistics as in the并像上面的run()
function above.run()
函数那样收集分析统计信息。
-
class
profile.
Profile
(timer=None, timeunit=0.0, subcalls=True, builtins=True)¶ This class is normally only used if more precise control over profiling is needed than what the通常,只有当需要比cProfile.run()
function provides.cProfile.run()
函数提供的更精确的分析控制时,才使用此类。A custom timer can be supplied for measuring how long code takes to run via the timer argument.可以提供自定义计时器,用于通过timer参数测量代码运行所需的时间。This must be a function that returns a single number representing the current time.这必须是一个返回表示当前时间的单个数字的函数。If the number is an integer, the timeunit specifies a multiplier that specifies the duration of each unit of time.如果数字是整数,则timeunit指定一个乘数,用于指定每个时间单位的持续时间。For example, if the timer returns times measured in thousands of seconds, the time unit would be例如,如果计时器返回以千秒为单位的时间,则时间单位为.001
..001
。Directly using the直接使用Profile
class allows formatting profile results without writing the profile data to a file:Profile
类可以格式化配置文件结果,而无需将配置文件数据写入文件:import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())The
Profile
class can also be used as a context manager (supported only incProfile
module. see Context Manager Types):import cProfile
with cProfile.Profile() as pr:
# ... do something ...
pr.print_stats()Changed in version 3.8:版本3.8中更改: Added context manager support.-
create_stats
()¶ Stop collecting profiling data and record the results internally as the current profile.
-
print_stats
(sort=- 1)¶ Create a
Stats
object based on the current profile and print the results to stdout.
-
dump_stats
(filename)¶ Write the results of the current profile to filename.
-
runctx
(cmd, globals, locals)¶ Profile the cmd via
exec()
with the specified global and local environment.
-
runcall
(func, /, *args, **kwargs)¶ Profile
func(*args, **kwargs)
-
Note that profiling will only work if the called command/function actually returns. If the interpreter is terminated (e.g. via a sys.exit()
call during the called command/function execution) no profiling results will be printed.
The Stats
Class¶
Analysis of the profiler data is done using the Stats
class.
-
class
pstats.
Stats
(*filenames or profile, stream=sys.stdout)¶ This class constructor creates an instance of a “statistics object” from a filename (or list of filenames) or from a
Profile
instance. Output will be printed to the stream specified by stream.The file selected by the above constructor must have been created by the corresponding version of
profile
orcProfile
. To be specific, there is no file compatibility guaranteed with future versions of this profiler, and there is no compatibility with files produced by other profilers, or the same profiler run on a different operating system. If several files are provided, all the statistics for identical functions will be coalesced, so that an overall view of several processes can be considered in a single report. If additional files need to be combined with data in an existingStats
object, theadd()
method can be used.Instead of reading the profile data from a file, a
cProfile.Profile
orprofile.Profile
object can be used as the profile data source.Stats
objects have the following methods:-
strip_dirs
()¶ This method for the
Stats
class removes all leading path information from file names. It is very useful in reducing the size of the printout to fit within (close to) 80 columns. This method modifies the object, and the stripped information is lost. After performing a strip operation, the object is considered to have its entries in a “random” order, as it was just after object initialization and loading. Ifstrip_dirs()
causes two function names to be indistinguishable (they are on the same line of the same filename, and have the same function name), then the statistics for these two entries are accumulated into a single entry.
-
add
(*filenames)¶ This method of the
Stats
class accumulates additional profiling information into the current profiling object. Its arguments should refer to filenames created by the corresponding version ofprofile.run()
orcProfile.run()
.Statistics for identically named (re: file, line, name) functions are automatically accumulated into single function statistics.同名(re:file、line、name)函数的统计信息自动累积到单个函数统计信息中。
-
dump_stats
(filename)¶ Save the data loaded into the
Stats
object to a file named filename. The file is created if it does not exist, and is overwritten if it already exists. This is equivalent to the method of the same name on theprofile.Profile
andcProfile.Profile
classes.
-
sort_stats
(*keys)¶ This method modifies the
Stats
object by sorting it according to the supplied criteria. The argument can be either a string or a SortKey enum identifying the basis of a sort (example:'time'
,'name'
,SortKey.TIME
orSortKey.NAME
).The SortKey enums argument have advantage over the string argument in that it is more robust and less error prone.SortKey enums参数比字符串参数有优势,因为它更健壮,更不容易出错。When more than one key is provided, then additional keys are used as secondary criteria when there is equality in all keys selected before them.当提供了多个键时,当在它们之前选择的所有键都相等时,将使用其他键作为次要标准。For example,sort_stats(SortKey.NAME, SortKey.FILE)
will sort all the entries according to their function name, and resolve all ties (identical function names) by sorting by file name.For the string argument, abbreviations can be used for any key names, as long as the abbreviation is unambiguous.对于字符串参数,缩写可以用于任何键名称,只要缩写明确即可。The following are the valid string and SortKey:以下是有效的字符串和SortKey:Valid String Arg
Valid enum Arg
Meaning
'calls'
SortKey.CALLS
call count
'cumulative'
SortKey.CUMULATIVE
cumulative time
'cumtime'
N/A
cumulative time
'file'
N/A
file name
'filename'
SortKey.FILENAME
file name
'module'
N/A
file name
'ncalls'
N/A
call count
'pcalls'
SortKey.PCALLS
primitive call count
'line'
SortKey.LINE
line number
'name'
SortKey.NAME
function name
'nfl'
SortKey.NFL
name/file/line
'stdname'
SortKey.STDNAME
standard name
'time'
SortKey.TIME
internal time
'tottime'
N/A
internal time
Note that all sorts on statistics are in descending order (placing most time consuming items first), where as name, file, and line number searches are in ascending order (alphabetical). The subtle distinction between
SortKey.NFL
andSortKey.STDNAME
is that the standard name is a sort of the name as printed, which means that the embedded line numbers get compared in an odd way. For example, lines 3, 20, and 40 would (if the file names were the same) appear in the string order 20, 3 and 40. In contrast,SortKey.NFL
does a numeric compare of the line numbers. In fact,sort_stats(SortKey.NFL)
is the same assort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE)
.For backward-compatibility reasons, the numeric arguments
-1
,0
,1
, and2
are permitted. They are interpreted as'stdname'
,'calls'
,'time'
, and'cumulative'
respectively. If this old style format (numeric) is used, only one sort key (the numeric key) will be used, and additional arguments will be silently ignored.New in version 3.7.版本3.7中新增。Added the SortKey enum.
-
reverse_order
()¶ This method for theStats
class reverses the ordering of the basic list within the object. Note that by default ascending vs descending order is properly selected based on the sort key of choice.Stats
类的此方法反转对象内基本列表的顺序。注意,默认情况下,根据选择的排序键正确选择升序和降序。
-
print_stats
(*restrictions)¶ This method for the
Stats
class prints out a report as described in theprofile.run()
definition.The order of the printing is based on the last
sort_stats()
operation done on the object (subject to caveats inadd()
andstrip_dirs()
).The arguments provided (if any) can be used to limit the list down to the significant entries.提供的参数(如果有)可用于将列表限制为有效条目。Initially, the list is taken to be the complete set of profiled functions.最初,该列表被认为是一组完整的被分析函数。Each restriction is either an integer (to select a count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines), or a string that will interpreted as a regular expression (to pattern match the standard name that is printed).每个限制要么是整数(选择行数),要么是介于0.0和1.0之间的小数(包括0.0和1.0)(选择行的百分比),要么就是将被解释为正则表达式的字符串(以模式匹配打印的标准名称)。If several restrictions are provided, then they are applied sequentially.如果提供了几个限制,则将依次应用这些限制。For example:例如:print_stats(.1, 'foo:')
would first limit the printing to first 10% of list, and then only print functions that were part of filename将首先将打印限制在列表的前10%,然后只打印属于文件名.*foo:
..*foo:
的函数。In contrast, the command:相反,命令:print_stats('foo:', .1)
would limit the list to all functions having file names将列表限制为具有文件名.*foo:
, and then proceed to only print the first 10% of them..*foo:
的所有函数,然后继续只打印其中的前10%。
-
print_callers
(*restrictions)¶ This method for the
Stats
class prints a list of all functions that called each function in the profiled database. The ordering is identical to that provided byprint_stats()
, and the definition of the restricting argument is also identical. Each caller is reported on its own line.The format differs slightly depending on the profiler that produced the stats:根据生成统计数据的探查器,格式略有不同:With对于profile
, a number is shown in parentheses after each caller to show how many times this specific call was made.profile
,每个调用方后面的括号中都会显示一个数字,以显示该特定呼叫的次数。For convenience, a second non-parenthesized number repeats the cumulative time spent in the function at the right.为了方便起见,第二个无括号的数字重复在右侧函数中花费的累积时间。With
cProfile
, each caller is preceded by three numbers: the number of times this specific call was made, and the total and cumulative times spent in the current function while it was invoked by this specific caller.
-
print_callees
(*restrictions)¶ This method for the
Stats
class prints a list of all function that were called by the indicated function. Aside from this reversal of direction of calls (re: called vs was called by), the arguments and ordering are identical to theprint_callers()
method.
-
get_stats_profile
()¶ This method returns an instance of StatsProfile, which contains a mapping of function names to instances of FunctionProfile. Each FunctionProfile instance holds information related to the function’s profile such as how long the function took to run, how many times it was called, etc…
New in version 3.9.版本3.9中新增。Added the following dataclasses: StatsProfile, FunctionProfile. Added the following function: get_stats_profile.
-
What Is Deterministic Profiling?¶
Deterministic profiling is meant to reflect the fact that all function call, function return, and exception events are monitored, and precise timings are made for the intervals between these events (during which time the user’s code is executing). In contrast, statistical profiling (which is not done by this module) randomly samples the effective instruction pointer, and deduces where time is being spent. The latter technique traditionally involves less overhead (as the code does not need to be instrumented), but provides only relative indications of where time is being spent.
In Python, since there is an interpreter active during execution, the presence of instrumented code is not required in order to do deterministic profiling. Python automatically provides a hook (optional callback) for each event. In addition, the interpreted nature of Python tends to add so much overhead to execution, that deterministic profiling tends to only add small processing overhead in typical applications. The result is that deterministic profiling is not that expensive, yet provides extensive run time statistics about the execution of a Python program.
Call count statistics can be used to identify bugs in code (surprising counts), and to identify possible inline-expansion points (high call counts). Internal time statistics can be used to identify “hot loops” that should be carefully optimized. Cumulative time statistics should be used to identify high level errors in the selection of algorithms. Note that the unusual handling of cumulative times in this profiler allows statistics for recursive implementations of algorithms to be directly compared to iterative implementations.
Limitations¶
One limitation has to do with accuracy of timing information. There is a fundamental problem with deterministic profilers involving accuracy. The most obvious restriction is that the underlying “clock” is only ticking at a rate (typically) of about .001 seconds. Hence no measurements will be more accurate than the underlying clock. If enough measurements are taken, then the “error” will tend to average out. Unfortunately, removing this first error induces a second source of error.
The second problem is that it “takes a while” from when an event is dispatched until the profiler’s call to get the time actually gets the state of the clock. Similarly, there is a certain lag when exiting the profiler event handler from the time that the clock’s value was obtained (and then squirreled away), until the user’s code is once again executing. As a result, functions that are called many times, or call many functions, will typically accumulate this error. The error that accumulates in this fashion is typically less than the accuracy of the clock (less than one clock tick), but it can accumulate and become very significant.
The problem is more important with profile
than with the lower-overhead cProfile
. For this reason, profile
provides a means of calibrating itself for a given platform so that this error can be probabilistically (on the average) removed. After the profiler is calibrated, it will be more accurate (in a least square sense), but it will sometimes produce negative numbers (when call counts are exceptionally low, and the gods of probability work against you :-). ) Do not be alarmed by negative numbers in the profile. They should only appear if you have calibrated your profiler, and the results are actually better than without calibration.
Calibration¶
The profiler of the profile
module subtracts a constant from each event handling time to compensate for the overhead of calling the time function, and socking away the results. By default, the constant is 0. The following procedure can be used to obtain a better constant for a given platform (see Limitations).
import profile
pr = profile.Profile()
for i in range(5):
print(pr.calibrate(10000))
The method executes the number of Python calls given by the argument, directly and again under the profiler, measuring the time for both. It then computes the hidden overhead per profiler event, and returns that as a float. For example, on a 1.8Ghz Intel Core i5 running macOS, and using Python’s time.process_time() as the timer, the magical number is about 4.04e-6.
The object of this exercise is to get a fairly consistent result. If your computer is very fast, or your timer function has poor resolution, you might have to pass 100000, or even 1000000, to get consistent results.
When you have a consistent answer, there are three ways you can use it:
import profile
# 1. Apply computed bias to all Profile instances created hereafter.
profile.Profile.bias = your_computed_bias
# 2. Apply computed bias to a specific Profile instance.
pr = profile.Profile()
pr.bias = your_computed_bias
# 3. Specify computed bias in instance constructor.
pr = profile.Profile(bias=your_computed_bias)
If you have a choice, you are better off choosing a smaller constant, and then your results will “less often” show up as negative in profile statistics.
Using a custom timer¶
If you want to change how current time is determined (for example, to force use of wall-clock time or elapsed process time), pass the timing function you want to the Profile
class constructor:
pr = profile.Profile(your_time_func)
The resulting profiler will then call your_time_func
. Depending on whether you are using profile.Profile
or cProfile.Profile
, your_time_func
’s return value will be interpreted differently:
profile.Profile
your_time_func
should return a single number, or a list of numbers whose sum is the current time (like whatos.times()
returns). If the function returns a single time number, or the list of returned numbers has length 2, then you will get an especially fast version of the dispatch routine.Be warned that you should calibrate the profiler class for the timer function that you choose (see Calibration). For most machines, a timer that returns a lone integer value will provide the best results in terms of low overhead during profiling. (
os.times()
is pretty bad, as it returns a tuple of floating point values). If you want to substitute a better timer in the cleanest fashion, derive a class and hardwire a replacement dispatch method that best handles your timer call, along with the appropriate calibration constant.cProfile.Profile
your_time_func
should return a single number. If it returns integers, you can also invoke the class constructor with a second argument specifying the real duration of one unit of time. For example, ifyour_integer_time_func
returns times measured in thousands of seconds, you would construct theProfile
instance as follows:pr = cProfile.Profile(your_integer_time_func, 0.001)
As the
cProfile.Profile
class cannot be calibrated, custom timer functions should be used with care and should be as fast as possible. For the best results with a custom timer, it might be necessary to hard-code it in the C source of the internal_lsprof
module.
Python 3.3 adds several new functions in time
that can be used to make precise measurements of process or wall-clock time. For example, see time.perf_counter()
.