<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](trace.xhtml "trace --- Trace or track Python statement execution") | - [上一頁](profile.xhtml "The Python Profilers") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [調試和分析](debug.xhtml) ? - $('.inline-search').show(0); | # [`timeit`](#module-timeit "timeit: Measure the execution time of small code snippets.") --- 測量小代碼片段的執行時間 **源碼:** [Lib/timeit.py](https://github.com/python/cpython/tree/3.7/Lib/timeit.py) \[https://github.com/python/cpython/tree/3.7/Lib/timeit.py\] - - - - - - 該模塊提供了一種簡單的方法來計算一小段 Python 代碼的耗時。它有 [命令行界面](#timeit-command-line-interface) 以及一個 [可調用](#python-interface) 方法。它避免了許多用于測量執行時間的常見陷阱。另見 Tim Peters 對 O'Reilly 出版的 *Python Cookbook* 中“算法”章節的介紹。 ## 基本示例 以下示例顯示了如何使用 [命令行界面](#timeit-command-line-interface) 來比較三個不同的表達式: ``` $ python3 -m timeit '"-".join(str(n) for n in range(100))' 10000 loops, best of 5: 30.2 usec per loop $ python3 -m timeit '"-".join([str(n) for n in range(100)])' 10000 loops, best of 5: 27.5 usec per loop $ python3 -m timeit '"-".join(map(str, range(100)))' 10000 loops, best of 5: 23.2 usec per loop ``` 這可以通過 [Python 接口](#python-interface) 實現 ``` >>> import timeit >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 0.3018611848820001 >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) 0.2727368790656328 >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000) 0.23702679807320237 ``` A callable can also be passed from the [Python 接口](#python-interface): ``` >>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000) 0.19665591977536678 ``` Note however that [`timeit()`](#timeit.timeit "timeit.timeit") will automatically determine the number of repetitions only when the command-line interface is used. In the [示例](#timeit-examples) section you can find more advanced examples. ## Python 接口 該模塊定義了三個便利函數和一個公共類: `timeit.``timeit`(*stmt='pass'*, *setup='pass'*, *timer=<default timer>*, *number=1000000*, *globals=None*)使用給定語句、 *setup* 代碼和 *timer* 函數創建一個 [`Timer`](#timeit.Timer "timeit.Timer") 實例,并執行 *number* 次其 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 方法。可選的 *globals* 參數指定用于執行代碼的命名空間。 在 3.5 版更改: 添加可選參數 *globals* 。 `timeit.``repeat`(*stmt='pass'*, *setup='pass'*, *timer=<default timer>*, *repeat=5*, *number=1000000*, *globals=None*)使用給定語句、 *setup* 代碼和 *timer* 函數創建一個 [`Timer`](#timeit.Timer "timeit.Timer") 實例,并使用給定的 *repeat* 計數和 *number* 執行運行其 [`repeat()`](#timeit.Timer.repeat "timeit.Timer.repeat") 方法。可選的 *globals* 參數指定用于執行代碼的命名空間。 在 3.5 版更改: 添加可選參數 *globals* 。 在 3.7 版更改: *repeat* 的默認值由 3 更改為 5 。 `timeit.``default_timer`()默認的計時器,總是 [`time.perf_counter()`](time.xhtml#time.perf_counter "time.perf_counter") 。 在 3.3 版更改: [`time.perf_counter()`](time.xhtml#time.perf_counter "time.perf_counter") 現在是默認計時器。 *class* `timeit.``Timer`(*stmt='pass'*, *setup='pass'*, *timer=<timer function>*, *globals=None*)用于小代碼片段的計數執行速度的類。 構造函數接受一個將計時的語句、一個用于設置的附加語句和一個定時器函數。兩個語句都默認為 `'pass'` ;計時器函數與平臺有關(請參閱模塊文檔字符串)。 *stmt* 和 *setup* 也可能包含多個以 `;` 或換行符分隔的語句,只要它們不包含多行字符串文字即可。該語句默認在 timeit 的命名空間內執行;可以通過將命名空間傳遞給 *globals* 來控制此行為。 要測量第一個語句的執行時間,請使用 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 方法。 [`repeat()`](#timeit.Timer.repeat "timeit.Timer.repeat") 和 [`autorange()`](#timeit.Timer.autorange "timeit.Timer.autorange") 方法是方便的方法來調用 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 多次。 *setup* 的執行時間從總體計時執行中排除。 *stmt* 和 *setup* 參數也可以使用不帶參數的可調用對象。這將在一個計時器函數中嵌入對它們的調用,然后由 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 執行。請注意,由于額外的函數調用,在這種情況下,計時開銷會略大一些。 在 3.5 版更改: 添加可選參數 *globals* 。 `timeit`(*number=1000000*)執行 *number* 次主要語句。這將執行一次 setup 語句,然后返回執行主語句多次所需的時間,以秒為單位測量為浮點數。參數是通過循環的次數,默認為一百萬。要使用的主語句、 setup 語句和 timer 函數將傳遞給構造函數。 注解 默認情況下, [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 暫時關閉 [garbage collection](../glossary.xhtml#term-garbage-collection) 。這種方法的優點在于它使獨立時序更具可比性。缺點是GC可能是所測量功能性能的重要組成部分。如果是這樣,可以在 *setup* 字符串中的第一個語句重新啟用GC。例如: ``` timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit() ``` `autorange`(*callback=None*)自動決定調用多少次 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 。 這是一個便利函數,它反復調用 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") ,以便總時間 >= 0.2 秒,返回最終(循環次數,循環所用的時間)。它調用 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 的次數以序列 1, 2, 5, 10, 20, 50, ... 遞增,直到所用的時間至少為0.2秒。 如果給出 *callback* 并且不是 `None` ,則在每次試驗后將使用兩個參數調用它: `callback(number, time_taken)` 。 3\.6 新版功能. `repeat`(*repeat=5*, *number=1000000*)調用 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 幾次。 這是一個方便的函數,它反復調用 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") ,返回結果列表。第一個參數指定調用 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 的次數。第二個參數指定 [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") 的 *number* 參數。 注解 從結果向量計算并報告平均值和標準差這些是很誘人的。但是,這不是很有用。在典型情況下,最低值給出了機器運行給定代碼段的速度的下限;結果向量中較高的值通常不是由Python的速度變化引起的,而是由于其他過程干擾你的計時準確性。所以結果的 [`min()`](functions.xhtml#min "min") 可能是你應該感興趣的唯一數字。之后,你應該看看整個向量并應用常識而不是統計。 在 3.7 版更改: *repeat* 的默認值由 3 更改為 5 。 `print_exc`(*file=None*)幫助程序從計時代碼中打印回溯。 典型使用: ``` t = Timer(...) # outside the try/except try: t.timeit(...) # or t.repeat(...) except Exception: t.print_exc() ``` 與標準回溯相比,優勢在于將顯示已編譯模板中的源行。可選的 *file* 參數指向發送回溯的位置;它默認為 [`sys.stderr`](sys.xhtml#sys.stderr "sys.stderr") 。 ## 命令行界面 從命令行調用程序時,使用以下表單: ``` python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...] ``` 如果了解以下選項: `-n`` N``, ``--number``=N`執行 '語句' 多少次 `-r`` N``, ``--repeat``=N`重復計時器的次數(默認為5) `-s`` S``, ``--setup``=S`最初要執行一次的語句(默認為 `pass` ) `-p````, ``--process```測量進程時間,而不是 wallclock 時間,使用 [`time.process_time()`](time.xhtml#time.process_time "time.process_time") 而不是 [`time.perf_counter()`](time.xhtml#time.perf_counter "time.perf_counter") ,這是默認值 3\.3 新版功能. `-u````, ``--unit``=U`> 指定定時器輸出的時間單位;可以選擇 nsec,usec,msec或sec 3\.5 新版功能. `-v````, ``--verbose```打印原始計時結果;重復更多位數精度 `-h````, ``--help```打印一條簡短的使用信息并退出 可以通過將每一行指定為單獨的語句參數來給出多行語句;通過在引號中包含參數并使用前導空格可以縮進行。多個 [`-s`](#cmdoption-timeit-s) 選項的處理方式相似。 如果 [`-n`](#cmdoption-timeit-n) 未給出,則通過嘗試10的連續冪次來計算合適數量的循環,直到總時間至少為 0.2 秒。 [`default_timer()`](#timeit.default_timer "timeit.default_timer") 測量可能受到在同一臺機器上運行的其他程序的影響,因此在需要精確計時時最好的做法是重復幾次計時并使用最佳時間。 [`-r`](#cmdoption-timeit-r) 選項對此有利;在大多數情況下,默認的 5 次重復可能就足夠了。 你可以使用 [`time.process_time()`](time.xhtml#time.process_time "time.process_time") 來測量CPU時間。 注解 執行 pass 語句會產生一定的基線開銷。這里的代碼不會試圖隱藏它,但你應該知道它。可以通過不帶參數調用程序來測量基線開銷,并且Python版本之間可能會有所不同。 ## 示例 可以提供一個在開頭只執行一次的 setup 語句: ``` $ python -m timeit -s 'text = "sample string"; char = "g"' 'char in text' 5000000 loops, best of 5: 0.0877 usec per loop $ python -m timeit -s 'text = "sample string"; char = "g"' 'text.find(char)' 1000000 loops, best of 5: 0.342 usec per loop ``` ``` >>> import timeit >>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"') 0.41440500499993504 >>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"') 1.7246671520006203 ``` 使用 [`Timer`](#timeit.Timer "timeit.Timer") 類及其方法可以完成同樣的操作: ``` >>> import timeit >>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"') >>> t.timeit() 0.3955516149999312 >>> t.repeat() [0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886] ``` 以下示例顯示如何計算包含多行的表達式。 在這里我們對比使用 [`hasattr()`](functions.xhtml#hasattr "hasattr") 與 [`try`](../reference/compound_stmts.xhtml#try)/[`except`](../reference/compound_stmts.xhtml#except) 的開銷來測試缺失與提供對象屬性: ``` $ python -m timeit 'try:' ' str.__bool__' 'except AttributeError:' ' pass' 20000 loops, best of 5: 15.7 usec per loop $ python -m timeit 'if hasattr(str, "__bool__"): pass' 50000 loops, best of 5: 4.26 usec per loop $ python -m timeit 'try:' ' int.__bool__' 'except AttributeError:' ' pass' 200000 loops, best of 5: 1.43 usec per loop $ python -m timeit 'if hasattr(int, "__bool__"): pass' 100000 loops, best of 5: 2.23 usec per loop ``` ``` >>> import timeit >>> # attribute is missing >>> s = """\ ... try: ... str.__bool__ ... except AttributeError: ... pass ... """ >>> timeit.timeit(stmt=s, number=100000) 0.9138244460009446 >>> s = "if hasattr(str, '__bool__'): pass" >>> timeit.timeit(stmt=s, number=100000) 0.5829014980008651 >>> >>> # attribute is present >>> s = """\ ... try: ... int.__bool__ ... except AttributeError: ... pass ... """ >>> timeit.timeit(stmt=s, number=100000) 0.04215312199994514 >>> s = "if hasattr(int, '__bool__'): pass" >>> timeit.timeit(stmt=s, number=100000) 0.08588060699912603 ``` 要讓 [`timeit`](#module-timeit "timeit: Measure the execution time of small code snippets.") 模塊訪問你定義的函數,你可以傳遞一個包含 import 語句的 *setup* 參數: ``` def test(): """Stupid test function""" L = [i for i in range(100)] if __name__ == '__main__': import timeit print(timeit.timeit("test()", setup="from __main__ import test")) ``` 另一種選擇是將 [`globals()`](functions.xhtml#globals "globals") 傳遞給 *globals* 參數,這將導致代碼在當前的全局命名空間中執行。這比單獨指定 import 更方便 ``` def f(x): return x**2 def g(x): return x**4 def h(x): return x**8 import timeit print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals())) ``` ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](trace.xhtml "trace --- Trace or track Python statement execution") | - [上一頁](profile.xhtml "The Python Profilers") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [調試和分析](debug.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看