Mã Python đồng hồ bấm giờ

Đồng hồ bấm giờ được sử dụng để đo khoảng thời gian giữa hai sự kiện thường tính bằng giây đến phút. Nó có nhiều cách sử dụng khác nhau như trong thể thao hoặc đo lưu lượng nhiệt, dòng điện, v.v. trong thiết lập công nghiệp. Python có thể được sử dụng để tạo đồng hồ bấm giờ bằng cách sử dụng thư viện tkinter của nó

Thư viện này sẽ có các tính năng GUI để tạo đồng hồ bấm giờ hiển thị tùy chọn  Bắt đầu, Dừng và Đặt lại . Thành phần chính của chương trình là sử dụng nhãn. mô-đun after[] của tkinter

label.after[parent, ms, function = None]
where
parent: The object of the widget which is using this function.
ms: Time in miliseconds.
function: Call back function

Trong chương trình dưới đây, chúng tôi sử dụng phương thức này làm thành phần chính của chương trình và thiết kế một tiện ích hiển thị các tính năng GUI trong đồng hồ bấm giờ

Mặc dù nhiều nhà phát triển công nhận Python là ngôn ngữ lập trình hiệu quả, nhưng các chương trình Python thuần túy có thể chạy chậm hơn so với các chương trình đối tác của chúng trong các ngôn ngữ được biên dịch như C, Rust và Java. Trong hướng dẫn này, bạn sẽ học cách sử dụng bộ hẹn giờ Python để theo dõi tốc độ chạy chương trình của bạn

Trong hướng dẫn này, bạn sẽ học cách sử dụng

  •  1# timer.py
     2
     3import time
     4
     5class TimerError[Exception]:
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__[self]:
    10        self._start_time = None
    11
    12    def start[self]:
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
    16
    17        self._start_time = time.perf_counter[]
    18
    19    def stop[self]:
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
    23
    24        elapsed_time = time.perf_counter[] - self._start_time
    25        self._start_time = None
    26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
    
    3 để đo thời gian trong Python
  • Các lớp để giữ trạng thái
  • Trình quản lý ngữ cảnh để làm việc với một khối mã
  • Trang trí để tùy chỉnh một chức năng

Bạn cũng sẽ có được kiến ​​thức cơ bản về cách hoạt động của các lớp, trình quản lý ngữ cảnh và trình trang trí. Khi bạn khám phá các ví dụ về từng khái niệm, bạn sẽ được truyền cảm hứng để sử dụng một hoặc một vài trong số chúng trong mã của mình, để định thời gian thực thi mã, cũng như trong các ứng dụng khác. Mỗi phương pháp đều có ưu điểm của nó và bạn sẽ học cách sử dụng tùy thuộc vào tình huống. Ngoài ra, bạn sẽ có một bộ đếm thời gian Python đang hoạt động mà bạn có thể sử dụng để theo dõi các chương trình của mình

Người trang trí Bảng điểm hỏi đáp. Nhấp vào đây để có quyền truy cập vào nhật ký trò chuyện dài 25 trang từ phiên Hỏi & Đáp về người trang trí Python của chúng tôi trong Slack Cộng đồng Python thực, nơi chúng tôi đã thảo luận về các câu hỏi phổ biến về người trang trí

Bộ hẹn giờ Python

Trước tiên, bạn sẽ xem qua một số mã ví dụ mà bạn sẽ sử dụng trong suốt hướng dẫn. Sau đó, bạn sẽ thêm bộ hẹn giờ Python vào mã này để theo dõi hiệu suất của nó. Bạn cũng sẽ tìm hiểu một số cách đơn giản nhất để đo thời gian chạy của ví dụ này

Loại bỏ các quảng cáo

Chức năng hẹn giờ Python

Nếu bạn kiểm tra mô-đun

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
4 tích hợp trong Python, thì bạn sẽ nhận thấy một số chức năng có thể đo thời gian

Trăn 3. 7 đã giới thiệu một số chức năng mới, như , cũng như các phiên bản nano giây của tất cả các chức năng trên, được đặt tên bằng hậu tố

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
00. Ví dụ, là phiên bản nano giây của
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6. Bạn sẽ tìm hiểu thêm về các chức năng này sau. For now, note what the documentation has to say about
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6

Return the value [in fractional seconds] of a performance counter, i. e. a clock with the highest available resolution to measure a short duration. []

First, you’ll use

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 to create a Python timer. , you’ll compare this with other Python timer functions and learn why
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 is usually the best choice

Example. Download Tutorials

To better compare the different ways that you can add a Python timer to your code, you’ll apply different Python timer functions to the same code example throughout this tutorial. If you already have code that you’d like to measure, then feel free to follow the examples with that instead

The example that you’ll use in this tutorial is a short function that uses the

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
06 package to download the latest tutorials available here on Real Python. To learn more about the Real Python Reader and how it works, check out How to Publish an Open-Source Python Package to PyPI. You can install
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
06 on your system with
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
08

$ python -m pip install realpython-reader

Then, you can import the package as

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
09

You’ll store the example in a file named

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
10. The code consists of one function that downloads and prints the latest tutorial from Real Python

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
06 handles most of the hard work

  • Line 3 imports
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    12 from
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    06. This module contains functionality for downloading tutorials from the
  • Line 7 downloads the latest tutorial from Real Python. The number
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    14 is an offset, where
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    14 means the most recent tutorial,
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    16 is the previous tutorial, and so on
  • Line 8 prints the tutorial to the console
  • Line 11 calls
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    17 when you run the script

When you run this example, your output will typically look something like this

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *

The code may take a little while to run depending on your network, so you might want to use a Python timer to monitor the performance of the script

Your First Python Timer

Now you’ll add a bare-bones Python timer to the example with

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
3. Một lần nữa, đây là bộ đếm hiệu suất rất phù hợp để định thời gian cho các phần mã của bạn

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 measures the time in seconds from some unspecified moment in time, which means that the return value of a single call to the function isn’t useful. However, when you look at the difference between two calls to
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6, you can figure out how many seconds passed between the two calls

>>>

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793

In this example, you made two calls to

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 almost 4 seconds apart. You can confirm this by calculating the difference between the two outputs. 32315. 26 - 32311. 49 = 3. 77

You can now add a Python timer to the example code

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]

Note that you call

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 both before and after downloading the tutorial. You then print the time it took to download the tutorial by calculating the difference between the two calls

Note. In line 11, the

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
23 before the string indicates that this is an f-string, which is a convenient way to format a text string.
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
24 is a format specifier that says the number,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
25, should be printed as a decimal number with four decimals

For more information about f-strings, check out Python 3’s f-Strings. An Improved String Formatting Syntax

Now, when you run the example, you’ll see the elapsed time before the tutorial

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]

That’s it. You’ve covered the basics of timing your own Python code. In the rest of the tutorial, you’ll learn how you can wrap a Python timer into a class, a context manager, and a decorator to make it more consistent and convenient to use

Loại bỏ các quảng cáo

A Python Timer Class

Look back at how you added the Python timer to the example above. Note that you need at least one variable [

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
26] to store the state of the Python timer before you download the tutorial. After studying the code a little, you might also note that the three highlighted lines are added only for timing purposes. Now, you’ll create a class that does the same as your manual calls to
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6, but in a more readable and consistent manner

Throughout this tutorial, you’ll create and update

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28, a class that you can use to time your code in several different ways. The final code with some additional features is also available on PyPI under the name
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
29. You can install this on your system like so

$ python -m pip install codetiming

You can find more information about

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
29 later on in this tutorial, in the section named

Understanding Classes in Python

Classes are the main building blocks of object-oriented programming. A class is essentially a template that you can use to create objects. While Python doesn’t force you to program in an object-oriented manner, classes are everywhere in the language. For quick proof, investigate the

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
4 module

>>>

>>> import time
>>> type[time]


>>> time.__class__

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
32 returns the type of an object. Here you can see that modules are, in fact, objects created from a
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
33 class. You can use the special attribute
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
34 to get access to the class that defines an object. In fact, almost everything in Python is a class

>>>

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

In Python, classes are great when you need to model something that needs to keep track of a particular state. In general, a class is a collection of properties, called attributes, and behaviors, called methods. For more background on classes and object-oriented programming, check out Object-Oriented Programming [OOP] in Python 3 or the official docs

Creating a Python Timer Class

Classes are good for tracking state. In a

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 class, you want to keep track of when a timer starts and how much time has passed since then. For the first implementation of
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28, you’ll add a
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
37 attribute, as well as
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
38 and
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
39 methods. Add the following code to a file named
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
40

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]

A few different things are happening here, so take a moment to walk through the code step by step

In line 5, you define a

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
41 class. The
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
42 notation means that
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
41 inherits from another class called
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
44. Python uses this built-in class for error handling. You don’t need to add any attributes or methods to
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
41, but having a custom error will give you more flexibility to handle problems inside
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28. For more information, check out Python Exceptions. An Introduction

The definition of

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 itself starts on line 8. When you first create or instantiate an object from a class, your code calls the special method
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
48. In this first version of
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28, you only initialize the
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
37 attribute, which you’ll use to track the state of your Python timer. It has the value
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
51 when the timer isn’t running. Khi bộ hẹn giờ đang chạy,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
37 theo dõi thời điểm bộ hẹn giờ bắt đầu

Note. Tiền tố gạch dưới [

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
53] của
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
37 là một quy ước của Python. Nó báo hiệu rằng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
37 là một thuộc tính bên trong mà người dùng của lớp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 không nên thao túng

Khi bạn gọi

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
38 để bắt đầu một bộ đếm thời gian Python mới, trước tiên bạn hãy kiểm tra xem bộ đếm thời gian chưa chạy chưa. Sau đó, bạn lưu trữ giá trị hiện tại của
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 trong
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
37

Mặt khác, khi bạn gọi

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
39, trước tiên bạn kiểm tra xem bộ hẹn giờ Python có đang chạy không. Nếu đúng như vậy, thì bạn tính thời gian đã trôi qua là chênh lệch giữa giá trị hiện tại của
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 và giá trị mà bạn lưu trữ trong
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
37. Cuối cùng, bạn đặt lại
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
37 để có thể khởi động lại bộ đếm thời gian và in thời gian đã trôi qua

Đây là cách bạn sử dụng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28

>>>

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
0

So sánh điều này với nơi bạn đã sử dụng trực tiếp

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6. Cấu trúc của mã khá giống nhau, nhưng bây giờ mã rõ ràng hơn và đây là một trong những lợi ích của việc sử dụng các lớp. By carefully choosing your class, method, and attribute names, you can make your code very descriptive

Loại bỏ các quảng cáo

Using the Python Timer Class

Now apply

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 to
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
10. You only need to make a few changes to your previous code

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
1

Notice that the code is very similar to what you used earlier. In addition to making the code more readable,

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 takes care of printing the elapsed time to the console, which makes the logging of time spent more consistent. When you run the code, you’ll get pretty much the same output

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
2

Printing the elapsed time from

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 may be consistent, but it seems that this approach is not very flexible. In the next section, you’ll see how to customize your class

Adding More Convenience and Flexibility

So far, you’ve learned that classes are suitable for when you want to encapsulate state and ensure consistent behavior in your code. In this section, you’ll add more convenience and flexibility to your Python timer

  • Use adaptable text and formatting when reporting the time spent
  • Apply flexible logging, either to the screen, to a log file, or other parts of your program
  • Create a Python timer that can accumulate over several invocations
  • Build an informative representation of a Python timer

First, see how you can customize the text used to report the time spent. In the previous code, the text

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
70 is hard-coded into
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
39. You can add flexibility to classes using instance variables, whose values are normally passed as arguments to
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
48 and stored as
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
73 attributes. For convenience, you can also provide reasonable default values

To add

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
74 as a
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 instance variable, you’ll do something like this in
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
40

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
3

Note that the default text,

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
77, is given as a regular string, not as an f-string. You can’t use an f-string here because f-strings evaluate immediately, and when you instantiate
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28, your code hasn’t yet calculated the elapsed time

Note. If you want to use an f-string to specify

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
74, then you need to use double curly braces to escape the curly braces that the actual elapsed time will replace

One example would be

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
80. If the value of
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
81 is
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
82, then this f-string would be evaluated as
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
83

In

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
39, you use
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
74 as a template and
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
86 to populate the template

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
4

After this update to

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
40, you can change the text as follows

>>>

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
5

Next, assume that you don’t just want to print a message to the console. Maybe you want to save your time measurements so that you can store them in a database. You can do this by returning the value of

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
88 from
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
39. Then, the calling code can choose to either ignore that return value or save it for later processing

Perhaps you want to integrate

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 into your logging routines. To support logging or other outputs from
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28, you need to change the call to
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
92 so that the user can supply their own logging function. This can be done similarly to how you customized the text earlier

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
6

Instead of using

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
92 directly, you create another instance variable in line 13,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
94, that should refer to a function that takes a string as an argument. In addition to
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
92, you can use functions like or
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
97 on . Also note the
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
98 test in line 25, which allows you to turn off printing completely by passing
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
99

Here are two examples that show the new functionality in action

>>>

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
7

When you run these examples in an interactive shell, Python prints the return value automatically

The third improvement that you’ll add is the ability to accumulate time measurements. You may want to do this, for example, when you’re calling a slow function in a loop. You’ll add a bit more functionality in the form of named timers with a dictionary that keeps track of every Python timer in your code

Assume that you’re expanding

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
10 to a
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
01 script that downloads and prints the ten latest tutorials from Real Python. The following is one possible implementation

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
8

The code loops over the numbers from 0 to 9 and uses those as offset arguments to

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
02. When you run the script, you’ll print a lot of information to your console

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
9

One subtle issue with this code is that you’re measuring not only the time it takes to download the tutorials, but also the time Python spends printing the tutorials to your screen. This might not be that important because the time spent printing should be negligible compared to the time spent downloading. Still, it would be good to have a way to precisely time what you’re after in these kinds of situations

Note. The time spent downloading ten tutorials is about the same as the time spent downloading one tutorial. This isn’t a bug in your code. Instead,

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
09 caches the Real Python feed the first time
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
04 is called, and reuses the information on later invocations

There are several ways that you can work around this without changing the current implementation of

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
05 However, supporting this use case will be quite useful, and you can do it with just a few lines of code

First, you’ll introduce a dictionary called

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
06 as a class variable on
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28, which means that all instances of
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 will share it. You implement it by defining it outside any methods

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
0

Class variables can be accessed either directly on the class or through an instance of the class

>>>

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
1

In both cases, the code returns the same empty class dictionary

Next, you’ll add optional names to your Python timer. You can use the name for two different purposes

  1. Looking up the elapsed time later in your code
  2. Accumulating timers with the same name

To add names to your Python timer, you need to make two more changes to

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
40. First,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 should accept
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
11 as a parameter. Second, the elapsed time should be added to
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
06 when a timer stops

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
2

Note that you use

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
13 when adding the new Python timer to
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
06. This is a great that only sets the value if
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
11 isn’t already defined in the dictionary. If
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
11 is already used in
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
06, then the value is left untouched. This allows you to accumulate several timers

>>>

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
3

You can now revisit

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
01 and make sure only the time spent on downloading the tutorials is measured

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
4

Rerunning the script will give output similar to earlier, although now you’re only timing the actual download of the tutorials

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
5

The final improvement that you’ll make to

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 is to make it more informative when you’re working with it interactively. Try the following

>>>

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
6

That last line is the default way that Python represents objects. While you can glean some information from it, it’s usually not very useful. Instead, it would be nice to see information like the name of

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28, or how it’ll report on the timings

In Python 3. 7, data classes were added to the standard library. These provide several conveniences to your classes, including a more informative representation string

Note. Các lớp dữ liệu chỉ được bao gồm trong Python cho phiên bản 3. 7 and later. However, there’s a backport available on PyPI for Python 3. 6

You can install it using

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
08

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
7

See Data Classes in Python 3. 7+ [Guide] for more information

Bạn chuyển đổi bộ đếm thời gian Python của mình thành một lớp dữ liệu bằng cách sử dụng trình trang trí

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
22. You’ll learn more about decorators . For now, you can think of this as a notation that tells Python that
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 is a data class

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
8

Mã này thay thế phương pháp

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
48 trước đó của bạn. Lưu ý cách các lớp dữ liệu sử dụng cú pháp tương tự như cú pháp biến lớp mà bạn đã thấy trước đó để xác định tất cả các biến. Trên thực tế,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
48 được tạo tự động cho các lớp dữ liệu, dựa trên định nghĩa của lớp

Bạn cần chú thích các biến của mình để sử dụng một lớp dữ liệu. Bạn có thể sử dụng chú thích này để thêm gợi ý loại vào mã của mình. Nếu bạn không muốn sử dụng gợi ý loại, thì thay vào đó, bạn có thể chú thích tất cả các biến bằng

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
26, giống như bạn đã làm ở trên. Bạn sẽ sớm học cách thêm gợi ý loại thực tế vào lớp dữ liệu của mình

Dưới đây là một vài lưu ý về lớp dữ liệu

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28

  • Dòng 9. Trình trang trí

    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    22 định nghĩa
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28 là một lớp dữ liệu

  • Dòng 11. Chú thích đặc biệt

    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    30 là cần thiết cho các lớp dữ liệu để xác định rằng
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    06 là một biến lớp

  • Dòng 12 đến 14.

    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    32,
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    74 và
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    34 sẽ được định nghĩa là thuộc tính trên
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28, có thể chỉ định giá trị của các giá trị này khi tạo phiên bản
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28. Tất cả đều có các giá trị mặc định nhất định

  • dòng 15. Nhớ lại rằng

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    37 là một thuộc tính đặc biệt được sử dụng để theo dõi trạng thái của bộ đếm thời gian Python, nhưng nó phải được ẩn khỏi người dùng. Sử dụng
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    38, bạn nói rằng nên loại bỏ
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    37 khỏi
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    48 và đại diện cho
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28

  • Dòng 17 đến 20. Bạn có thể sử dụng phương pháp đặc biệt

    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    42 cho bất kỳ khởi tạo nào mà bạn cần thực hiện ngoài việc thiết lập các thuộc tính thể hiện. Tại đây, bạn sử dụng nó để thêm bộ hẹn giờ đã đặt tên vào
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    06

Your new

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 data class works just like your previous regular class, except that it now has a nice representation

>>>

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
9

Now you have a pretty neat version of

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 that’s consistent, flexible, convenient, and informative. You can apply many of the improvements that you’ve made in this section to other types of classes in your projects as well

Before ending this section, revisit the complete source code of

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 as it currently stands. You’ll notice the addition of type hints to the code for extra documentation

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
0

Using a class to create a Python timer has several benefits

  • Readability. Your code will read more naturally if you carefully choose class and method names
  • Consistency. Your code will be easier to use if you encapsulate properties and behaviors into attributes and methods
  • Flexibility. Mã của bạn sẽ có thể tái sử dụng nếu bạn sử dụng các thuộc tính có giá trị mặc định thay vì các giá trị được mã hóa cứng

Lớp này rất linh hoạt và bạn có thể sử dụng nó trong hầu hết mọi tình huống mà bạn muốn theo dõi thời gian cần để mã chạy. Tuy nhiên, trong các phần tiếp theo, bạn sẽ tìm hiểu về cách sử dụng trình quản lý ngữ cảnh và trình trang trí, điều này sẽ thuận tiện hơn cho việc định thời gian cho các khối mã và chức năng

Loại bỏ các quảng cáo

Trình quản lý bối cảnh hẹn giờ Python

Lớp học Python

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 của bạn đã đi được một chặng đường dài. So với , mã của bạn đã trở nên khá mạnh mẽ. Tuy nhiên, vẫn còn một chút mã soạn sẵn cần thiết để sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 của bạn

  1. Đầu tiên, khởi tạo lớp
  2. Gọi
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    38 trước khối mã mà bạn muốn bấm giờ
  3. Gọi
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    39 sau khối mã

May mắn thay, Python có một cấu trúc duy nhất để gọi các hàm trước và sau một khối mã. trình quản lý bối cảnh. Trong phần này, bạn sẽ tìm hiểu trình quản lý bối cảnh và câu lệnh

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
51 của Python là gì và cách bạn có thể tạo trình quản lý ngữ cảnh của riêng mình. Sau đó, bạn sẽ mở rộng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 để nó cũng có thể hoạt động như một trình quản lý ngữ cảnh. Cuối cùng, bạn sẽ thấy cách sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 làm trình quản lý bối cảnh có thể đơn giản hóa mã của bạn

Hiểu Trình quản lý ngữ cảnh trong Python

Trình quản lý bối cảnh đã là một phần của Python trong một thời gian dài. Chúng được PEP 343 giới thiệu vào năm 2005 và lần đầu tiên được triển khai trong Python 2. 5. Bạn có thể nhận ra trình quản lý ngữ cảnh trong mã bằng cách sử dụng từ khóa

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
51

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
1

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
55 là một số biểu thức Python trả về trình quản lý bối cảnh. Trình quản lý bối cảnh được tùy chọn ràng buộc với tên
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
56. Cuối cùng,
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
57 là bất kỳ khối mã Python thông thường nào. Trình quản lý bối cảnh sẽ đảm bảo rằng chương trình của bạn gọi một số mã trước khi
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
57 và một số mã khác sau khi
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
57 thực thi. Điều sau sẽ xảy ra, ngay cả khi
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
57 đưa ra một ngoại lệ

Việc sử dụng phổ biến nhất của trình quản lý ngữ cảnh có thể là xử lý các tài nguyên khác nhau, như tệp, khóa và kết nối cơ sở dữ liệu. Sau đó, trình quản lý ngữ cảnh được sử dụng để giải phóng và dọn sạch tài nguyên sau khi bạn sử dụng xong. Ví dụ sau cho thấy cấu trúc cơ bản của

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
40 bằng cách chỉ in các dòng có chứa dấu hai chấm. Quan trọng hơn, nó hiển thị thành ngữ phổ biến để mở tệp bằng Python

>>>

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
2

Lưu ý rằng

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
62, con trỏ tệp, không bao giờ được đóng một cách rõ ràng vì bạn đã sử dụng
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
63 làm trình quản lý bối cảnh. Bạn có thể xác nhận rằng
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
62 đã tự động đóng

>>>

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
3

Trong ví dụ này,

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
65 là một biểu thức trả về trình quản lý ngữ cảnh. Trình quản lý bối cảnh đó bị ràng buộc với tên
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
62. Trình quản lý bối cảnh có hiệu lực trong quá trình thực hiện
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
92. Khối mã một dòng này thực thi trong ngữ cảnh của
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
62

Điều đó có nghĩa là gì khi

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
62 là người quản lý ngữ cảnh? . Có nhiều giao thức khác nhau nằm dưới ngôn ngữ Python. Bạn có thể nghĩ về một giao thức như một hợp đồng nêu rõ những phương pháp cụ thể mà mã của bạn phải triển khai

Bao gồm hai phương pháp

  1. Gọi
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    71 khi nhập ngữ cảnh liên quan đến trình quản lý ngữ cảnh
  2. Gọi
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    72 khi thoát khỏi bối cảnh liên quan đến trình quản lý bối cảnh

Nói cách khác, để tự tạo trình quản lý ngữ cảnh, bạn cần viết một lớp triển khai

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
71 và
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72. Không nhiều không ít. Hãy thử một Hello, World. ví dụ quản lý bối cảnh

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
4

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
75 là trình quản lý ngữ cảnh vì nó triển khai giao thức quản lý ngữ cảnh. Bạn có thể sử dụng nó như thế này

>>>

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
5

First, note how

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
71 is called before you’re doing stuff, while
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72 is called after. Trong ví dụ đơn giản này, bạn không tham khảo trình quản lý ngữ cảnh. Trong những trường hợp như vậy, bạn không cần đặt tên cho trình quản lý ngữ cảnh bằng
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
78

Tiếp theo, chú ý cách

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
71 trả về
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
73. Giá trị trả về của
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
71 bị ràng buộc bởi
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
78. Bạn thường muốn trả về
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
73 từ
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
71 khi tạo trình quản lý ngữ cảnh. Bạn có thể sử dụng giá trị trả về đó như sau

>>>

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
6

Cuối cùng,

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72 có ba đối số.
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
86,
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
87 và
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
88. Chúng được sử dụng để xử lý lỗi trong trình quản lý bối cảnh và chúng phản ánh

Nếu một ngoại lệ xảy ra trong khi khối đang được thực thi, thì mã của bạn sẽ gọi

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72 với loại ngoại lệ, một thể hiện ngoại lệ và một đối tượng truy nguyên. Thông thường, bạn có thể bỏ qua những điều này trong trình quản lý bối cảnh của mình, trong trường hợp đó,
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72 được gọi trước khi ngoại lệ được kích hoạt lại

>>>

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
7

Bạn có thể thấy rằng

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
92 được in, mặc dù có lỗi trong mã

Bây giờ bạn đã biết trình quản lý ngữ cảnh là gì và cách bạn có thể tạo trình quản lý ngữ cảnh của riêng mình. Nếu bạn muốn tìm hiểu sâu hơn, hãy xem

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
93 trong thư viện tiêu chuẩn. Nó bao gồm các cách thuận tiện để xác định trình quản lý ngữ cảnh mới, cũng như các trình quản lý ngữ cảnh được tạo sẵn mà bạn có thể sử dụng để , hoặc thậm chí. Để biết thêm thông tin, hãy xem Trình quản lý ngữ cảnh và Tuyên bố
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
51 của Python

Loại bỏ các quảng cáo

Tạo Trình quản lý bối cảnh hẹn giờ Python

Bạn đã thấy cách các trình quản lý ngữ cảnh hoạt động nói chung, nhưng chúng có thể trợ giúp như thế nào với mã thời gian? . Cho đến nay, bạn cần gọi rõ ràng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
38 và
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
39 khi định thời gian cho mã của mình, nhưng trình quản lý ngữ cảnh có thể tự động thực hiện việc này

Một lần nữa, để

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 hoạt động như một trình quản lý ngữ cảnh, nó cần tuân thủ giao thức của trình quản lý ngữ cảnh. Nói cách khác, nó phải triển khai
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
71 và
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72 để bắt đầu và dừng bộ hẹn giờ Python. Tất cả các chức năng cần thiết đã có sẵn, vì vậy bạn không cần phải viết nhiều mã mới. Chỉ cần thêm các phương thức sau vào lớp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 của bạn

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
8

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 hiện là người quản lý ngữ cảnh. Phần quan trọng của việc triển khai là
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
71 gọi
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
38 để bắt đầu bộ đếm thời gian Python khi ngữ cảnh được nhập và
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72 sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
39 để dừng bộ đếm thời gian Python khi mã rời khỏi ngữ cảnh. dùng thử

>>>

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
9

Bạn cũng nên lưu ý thêm hai chi tiết tinh tế

  1. $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    71 trả về
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    73, phiên bản
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28, cho phép người dùng liên kết phiên bản
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28 với một biến bằng cách sử dụng
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    78. Ví dụ,
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    11 sẽ tạo biến
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    12 trỏ đến đối tượng
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28

  2. $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ .. ]
    
    ## Read the full article at //realpython.com/python-timer/ »
    
    * * *
    
    72 mong đợi ba đối số với thông tin về bất kỳ ngoại lệ nào xảy ra trong quá trình thực thi ngữ cảnh. Trong mã của bạn, các đối số này được đóng gói thành một bộ có tên là
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    15 và sau đó bị bỏ qua, điều đó có nghĩa là
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28 sẽ không cố gắng xử lý ngoại lệ nào

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72 không xử lý lỗi trong trường hợp này. Tuy nhiên, một trong những tính năng tuyệt vời của trình quản lý ngữ cảnh là chúng được đảm bảo gọi ____22_______72, bất kể ngữ cảnh thoát ra như thế nào. Trong ví dụ sau, bạn cố tình tạo ra một lỗi bằng cách chia cho 0

>>>

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
0

Lưu ý rằng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 in ra thời gian đã trôi qua, mặc dù mã bị lỗi. Có thể kiểm tra và loại bỏ lỗi trong
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
72. Xem để biết thêm thông tin

Sử dụng Trình quản lý bối cảnh hẹn giờ Python

Bây giờ bạn sẽ học cách sử dụng trình quản lý ngữ cảnh

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 để tính thời gian tải xuống các hướng dẫn Real Python. Nhớ lại cách bạn đã sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 trước đó

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
1

Bạn đang tính thời gian cuộc gọi tới

$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

While many developers recognize Python as an effective programming language,
pure Python programs may run more slowly than their counterparts in compiled
languages like C, Rust, and Java. In this tutorial, you'll learn how to use
a Python timer to monitor how quickly your programs are running.

[ .. ]

## Read the full article at //realpython.com/python-timer/ »

* * *
02. Bạn có thể sử dụng trình quản lý bối cảnh để làm cho mã ngắn hơn, đơn giản hơn và dễ đọc hơn

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
2

Mã này hầu như giống như mã ở trên. Sự khác biệt chính là bạn không xác định biến ngoại lai

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
12, điều này giúp không gian tên của bạn sạch hơn

Chạy tập lệnh sẽ cho kết quả quen thuộc

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
3

Có một vài lợi thế khi thêm các khả năng của trình quản lý bối cảnh vào lớp bộ đếm thời gian Python của bạn

  • nỗ lực thấp. Bạn chỉ cần thêm một dòng mã để tính thời gian thực hiện một khối mã
  • khả năng đọc. Việc gọi trình quản lý bối cảnh có thể đọc được và bạn có thể hình dung rõ ràng hơn về khối mã mà bạn đang định thời gian

Sử dụng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 làm trình quản lý bối cảnh gần như linh hoạt như sử dụng trực tiếp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
38 và
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
39, trong khi nó có ít mã soạn sẵn hơn. Trong phần tiếp theo, bạn sẽ học cách sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 làm trang trí. Điều này sẽ giúp dễ dàng theo dõi thời gian chạy của các chức năng hoàn chỉnh hơn

Loại bỏ các quảng cáo

Trình trang trí bộ đếm thời gian Python

Lớp học

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 của bạn hiện rất linh hoạt. Tuy nhiên, có một trường hợp sử dụng mà bạn có thể hợp lý hóa nó hơn nữa. Giả sử bạn muốn theo dõi thời gian sử dụng bên trong một chức năng nhất định trong cơ sở mã của mình. Sử dụng trình quản lý bối cảnh, về cơ bản bạn có hai tùy chọn khác nhau

  1. Sử dụng

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28 mỗi khi bạn gọi hàm

     1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main[]:
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter[]
     9    tutorial = feed.get_article[0]
    10    toc = time.perf_counter[]
    11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
    12
    13    print[tutorial]
    14
    15if __name__ == "__main__":
    16    main[]
    
    4

    Nếu bạn gọi

    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    31 ở nhiều nơi, thì điều này sẽ trở nên cồng kềnh và khó duy trì

  2. Bọc mã trong chức năng của bạn bên trong trình quản lý ngữ cảnh

     1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main[]:
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter[]
     9    tutorial = feed.get_article[0]
    10    toc = time.perf_counter[]
    11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
    12
    13    print[tutorial]
    14
    15if __name__ == "__main__":
    16    main[]
    
    5

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28 chỉ cần được thêm vào một chỗ, nhưng điều này thêm một mức độ thụt lề cho toàn bộ định nghĩa của
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    31

Một giải pháp tốt hơn là sử dụng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 làm trang trí. Trình trang trí là các cấu trúc mạnh mẽ mà bạn sử dụng để sửa đổi hành vi của các hàm và lớp. Trong phần này, bạn sẽ tìm hiểu một chút về cách hoạt động của bộ trang trí, cách bạn có thể mở rộng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 thành bộ trang trí và cách điều đó sẽ đơn giản hóa các chức năng định thời. Để được giải thích sâu hơn về các công cụ trang trí, hãy xem Primer on Python Decorators

Hiểu về người trang trí trong Python

Trình trang trí là một chức năng bao bọc một chức năng khác để sửa đổi hành vi của nó. Kỹ thuật này có thể thực hiện được vì các hàm có trong Python. In other words, functions can be assigned to variables and used as arguments to other functions, just like any other object. Điều này mang lại cho bạn rất nhiều sự linh hoạt và là cơ sở cho một số tính năng mạnh mẽ nhất của Python

Ví dụ đầu tiên, bạn sẽ tạo một trình trang trí không làm gì cả

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
6

Đầu tiên, lưu ý rằng

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
36 chỉ là một hàm thông thường. Điều làm cho cái này trở thành một công cụ trang trí là nó nhận một hàm làm đối số duy nhất của nó và trả về một hàm. Bạn có thể sử dụng
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
36 để sửa đổi các chức năng khác, như thế này

>>>

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
7

Dòng

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
38 trang trí câu lệnh in với trang trí
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
36. Thực tế, nó thay thế
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
92 bằng
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
41 được trả về bởi
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
36. Câu lệnh lambda đại diện cho một hàm ẩn danh không làm gì ngoại trừ trả về
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
51

Để xác định các trình trang trí thú vị hơn, bạn cần biết về các chức năng bên trong. Hàm bên trong là một hàm được xác định bên trong một hàm khác. Một cách sử dụng phổ biến của các chức năng bên trong là tạo các nhà máy chức năng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
8

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
44 là một hàm bên trong, được xác định bên trong
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
45. Lưu ý rằng bạn có quyền truy cập vào
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
46 bên trong
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
44, trong khi
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
44 không được xác định bên ngoài
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
45

>>>

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
9

Thay vào đó, bạn sử dụng

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
45 để tạo các hàm số nhân mới, mỗi hàm dựa trên một yếu tố khác nhau

>>>

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
0

Tương tự, bạn có thể sử dụng các chức năng bên trong để tạo trang trí. Hãy nhớ rằng, một trình trang trí là một hàm trả về một hàm

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
1

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
51 là một công cụ trang trí, bởi vì nó là một hàm mong đợi một hàm,
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
52, làm đối số duy nhất của nó và trả về một hàm khác,
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
53. Lưu ý cấu trúc của chính
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
51

  • Dòng 1 bắt đầu định nghĩa của
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    51 và mong đợi một hàm làm đối số
  • Dòng 2 đến 5 xác định hàm bên trong
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    53
  • Dòng 6 trả về
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    53

Mẫu này là phổ biến để xác định trang trí. Các phần thú vị là những phần xảy ra bên trong chức năng bên trong

  • Dòng 2 bắt đầu định nghĩa của
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    53. Chức năng này sẽ thay thế bất kỳ chức năng nào
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    51 trang trí. Các tham số là
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    60 và
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    61, thu thập bất kỳ đối số vị trí và từ khóa nào bạn chuyển đến hàm. Điều này mang lại cho bạn sự linh hoạt để sử dụng
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    51 trên bất kỳ chức năng nào
  • Dòng 3 in ra tên của chức năng được trang trí và lưu ý rằng
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    51 đã được áp dụng cho nó
  • Dòng 4 gọi
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    52, chức năng mà
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    51 đã trang trí. Nó chuyển tất cả các đối số được chuyển đến
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    53
  • Dòng 5 nhân ba lần giá trị trả về của
    >>> import time
    >>> time.perf_counter[]
    32311.48899951
    
    >>> time.perf_counter[]  # A few seconds later
    32315.261320793
    
    52 và trả về nó

dùng thử.

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
68 là một hàm trả về từ
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
69. Xem điều gì xảy ra nếu nó tăng gấp ba lần

>>>

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
2

Nhân một chuỗi văn bản với một số là một hình thức lặp lại, do đó,

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
69 lặp lại ba lần. Việc trang trí diễn ra tại
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
71

Cảm giác hơi rắc rối khi cứ lặp đi lặp lại

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
72. Thay vào đó, PEP 318 đã giới thiệu một cú pháp thuận tiện hơn để áp dụng các trình trang trí. Định nghĩa sau đây của
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
68 giống như định nghĩa ở trên

>>>

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
3

Biểu tượng

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
74 được sử dụng để áp dụng trang trí. Trong trường hợp này,
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
75 có nghĩa là
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
51 được áp dụng cho hàm được xác định ngay sau nó

Một trong số ít decorator được định nghĩa trong thư viện chuẩn là

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
77. Điều này khá hữu ích khi xác định các trang trí của riêng bạn. Vì các công cụ trang trí thay thế chức năng này bằng chức năng khác một cách hiệu quả nên chúng tạo ra sự cố tế nhị với các chức năng của bạn

>>>

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
4

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
75 tô điểm cho
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
68, sau đó được thay thế bằng hàm bên trong
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
53, như đầu ra ở trên xác nhận. Điều này cũng sẽ thay thế tên, và siêu dữ liệu khác. Thông thường, điều này sẽ không có nhiều tác dụng, nhưng nó có thể gây khó khăn cho việc xem xét nội tâm.

Đôi khi, các chức năng được trang trí phải có siêu dữ liệu chính xác.

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
77 khắc phục chính xác vấn đề này

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
5

Với định nghĩa mới này của

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
75, siêu dữ liệu được giữ nguyên

>>>

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
6

Lưu ý rằng

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
68 hiện vẫn giữ tên riêng của nó, ngay cả sau khi được trang trí. Đó là hình thức tốt để sử dụng
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
77 bất cứ khi nào bạn xác định một người trang trí. Một kế hoạch chi tiết mà bạn có thể sử dụng cho hầu hết các nhà trang trí của mình là như sau

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
7

Để xem thêm ví dụ về cách xác định trình trang trí, hãy xem các ví dụ được liệt kê trong

Loại bỏ các quảng cáo

Tạo Trình trang trí bộ hẹn giờ Python

Trong phần này, bạn sẽ tìm hiểu cách mở rộng bộ hẹn giờ Python của mình để bạn cũng có thể sử dụng nó làm công cụ trang trí. Tuy nhiên, ở bài tập đầu tiên, bạn sẽ tạo một bộ trang trí bộ hẹn giờ Python từ đầu

Dựa trên kế hoạch chi tiết ở trên, bạn chỉ cần quyết định những việc cần làm trước và sau khi gọi hàm trang trí. Điều này tương tự như những cân nhắc về những việc cần làm khi vào và thoát khỏi trình quản lý bối cảnh. Bạn muốn bắt đầu bộ hẹn giờ Python trước khi gọi chức năng được trang trí và dừng bộ hẹn giờ Python sau khi cuộc gọi kết thúc. Bạn có thể định nghĩa a như sau

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
8

Lưu ý rằng

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
86 giống với mẫu trước đó mà bạn đã thiết lập để tính thời gian cho mã Python. Bạn có thể đăng ký
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
85 như sau

>>>

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
9

Nhớ lại rằng bạn cũng có thể áp dụng một trình trang trí cho một chức năng đã xác định trước đó

>>>

$ python -m pip install codetiming
0

Bởi vì

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
74 áp dụng khi các chức năng được xác định, bạn cần sử dụng biểu mẫu cơ bản hơn trong những trường hợp này. Một lợi thế của việc sử dụng trình trang trí là bạn chỉ cần áp dụng nó một lần và nó sẽ tính thời gian cho chức năng mỗi lần

>>>

$ python -m pip install codetiming
1

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
85 thực hiện công việc. Tuy nhiên, theo một nghĩa nào đó, bạn đang quay trở lại hình vuông, vì
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
85 không có bất kỳ sự linh hoạt hoặc tiện lợi nào của
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28. Bạn cũng có thể làm cho lớp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 của mình đóng vai trò như một người trang trí không?

Cho đến giờ, bạn đã sử dụng các bộ trang trí như các chức năng được áp dụng cho các chức năng khác, nhưng điều đó không hoàn toàn đúng. Trang trí phải được callables. Có rất nhiều trong Python. Bạn có thể làm cho các đối tượng của riêng mình có thể gọi được bằng cách định nghĩa phương thức đặc biệt

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
93 trong lớp của chúng. Hàm và lớp sau hoạt động tương tự

>>>

$ python -m pip install codetiming
2

Ở đây,

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
94 là một thể hiện có thể gọi được và có thể bình phương số, giống như hàm
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
95 trong ví dụ đầu tiên

Điều này cung cấp cho bạn một cách để thêm các khả năng của trình trang trí vào lớp

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 hiện có

$ python -m pip install codetiming
3

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
93 sử dụng thực tế rằng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 đã là người quản lý ngữ cảnh để tận dụng những tiện ích mà bạn đã xác định ở đó. Đảm bảo rằng bạn cũng nhập
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
99 ở đầu
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
40

Bây giờ bạn có thể sử dụng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 làm trang trí

>>>

$ python -m pip install codetiming
4

Trước khi kết thúc phần này, hãy biết rằng có một cách đơn giản hơn để biến bộ hẹn giờ Python của bạn thành một bộ trang trí. Bạn đã thấy một số điểm tương đồng giữa trình quản lý ngữ cảnh và trình trang trí. Cả hai thường được sử dụng để làm điều gì đó trước và sau khi thực thi một số mã nhất định

Dựa trên những điểm tương đồng này, có một định nghĩa trong thư viện tiêu chuẩn được gọi là. Bạn có thể thêm các khả năng trang trí vào các lớp trình quản lý ngữ cảnh của mình chỉ bằng cách kế thừa

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
02

$ python -m pip install codetiming
5

Khi bạn sử dụng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
02 theo cách này, bạn không cần phải tự triển khai
>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
93, vì vậy bạn có thể xóa nó khỏi lớp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 một cách an toàn

Loại bỏ các quảng cáo

Sử dụng Trình trang trí bộ hẹn giờ Python

Tiếp theo, bạn sẽ làm lại ví dụ

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
10 lần cuối, sử dụng bộ đếm thời gian Python làm công cụ trang trí

$ python -m pip install codetiming
6

Nếu bạn so sánh cách triển khai này với cách triển khai không có thời gian, thì bạn sẽ nhận thấy rằng sự khác biệt duy nhất là việc nhập

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 trên dòng 3 và ứng dụng của
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
09 trên dòng 6. Một lợi thế đáng kể của việc sử dụng các công cụ trang trí là chúng thường dễ áp ​​dụng, như bạn thấy ở đây

Tuy nhiên, decorator vẫn áp dụng cho toàn bộ chức năng. Điều này có nghĩa là mã của bạn đang tính đến thời gian cần thiết để in hướng dẫn, ngoài thời gian tải xuống. Chạy tập lệnh lần cuối

$ python -m pip install codetiming
7

Vị trí của đầu ra thời gian đã trôi qua là một dấu hiệu nhận biết rằng mã của bạn cũng đang xem xét thời gian in. Như bạn thấy ở đây, mã của bạn in thời gian đã trôi qua sau hướng dẫn

Khi bạn sử dụng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 làm công cụ trang trí, bạn sẽ thấy những lợi ích tương tự như bạn đã làm với trình quản lý ngữ cảnh

  • nỗ lực thấp. Bạn chỉ cần thêm một dòng mã để tính thời gian thực hiện một chức năng
  • khả năng đọc. Khi bạn thêm decorator, bạn có thể lưu ý rõ hơn là code của bạn sẽ tính thời gian cho hàm
  • Tính nhất quán. Bạn chỉ cần thêm trình trang trí khi chức năng được xác định. Mã của bạn sẽ nhất quán thời gian mỗi khi nó được gọi

However, decorators are not as flexible as context managers. Bạn chỉ có thể áp dụng chúng để hoàn thành chức năng. Có thể thêm các bộ trang trí vào các chức năng đã được xác định, nhưng điều này hơi rắc rối và ít phổ biến hơn

Mã hẹn giờ Python

Bạn có thể mở rộng khối mã bên dưới để xem mã nguồn cuối cùng cho bộ hẹn giờ Python của mình

Mã nguồn đầy đủ của hẹn giờ. pyHiện/Ẩn

$ python -m pip install codetiming
8

Mã này cũng có sẵn trong kho lưu trữ

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
29 trên GitHub

Bạn có thể tự mình sử dụng mã bằng cách lưu mã vào tệp có tên

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
40 và nhập mã vào chương trình của mình

>>>

$ python -m pip install codetiming
9

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 cũng có sẵn trên PyPI, vì vậy một tùy chọn thậm chí còn dễ dàng hơn là cài đặt nó bằng cách sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
08

$ python -m pip install codetiming

Lưu ý rằng tên gói trên PyPI là

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
29. Bạn sẽ cần sử dụng tên này cả khi bạn cài đặt gói và khi bạn nhập
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28

>>>

>>> import time
>>> type[time]


>>> time.__class__

1

Ngoài tên và một số tính năng bổ sung,

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
17 hoạt động chính xác như
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
18. Tóm lại, bạn có thể sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 theo ba cách khác nhau

  1. Như một lớp học

    >>> import time
    >>> type[time]
    
    
    >>> time.__class__
    
    
    2

  2. Là người quản lý bối cảnh

    >>> import time
    >>> type[time]
    
    
    >>> time.__class__
    
    
    3

  3. Là một người trang trí

    >>> import time
    >>> type[time]
    
    
    >>> time.__class__
    
    
    4

Loại bộ đếm thời gian Python này chủ yếu hữu ích để theo dõi thời gian mà mã của bạn dành cho các hàm hoặc khối mã khóa riêng lẻ. Trong phần tiếp theo, bạn sẽ có tổng quan nhanh về các lựa chọn thay thế mà bạn có thể sử dụng nếu muốn tối ưu hóa mã của mình

Loại bỏ các quảng cáo

Các chức năng hẹn giờ Python khác

Có nhiều tùy chọn để định thời gian mã của bạn với Python. Trong hướng dẫn này, bạn đã học cách tạo một lớp linh hoạt và thuận tiện mà bạn có thể sử dụng theo nhiều cách khác nhau. Tìm kiếm nhanh trên PyPI cho thấy đã có nhiều dự án cung cấp giải pháp hẹn giờ Python

Trong phần này, trước tiên bạn sẽ tìm hiểu thêm về các chức năng khác nhau có sẵn trong thư viện tiêu chuẩn để đo thời gian, bao gồm cả lý do tại sao nên dùng

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6. Sau đó, bạn sẽ khám phá các giải pháp thay thế để tối ưu hóa mã của mình, mà
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 không phù hợp

Sử dụng các hàm hẹn giờ Python thay thế

Bạn đã sử dụng

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 trong suốt hướng dẫn này để thực hiện các phép đo thời gian thực, nhưng thư viện
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
4 của Python đi kèm với một số hàm khác cũng đo thời gian. Đây là một số lựa chọn

Một lý do để có nhiều hàm là Python biểu thị thời gian dưới dạng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
28. Các số dấu phẩy động không chính xác về bản chất. Bạn có thể đã thấy kết quả như thế này trước đây

>>>

>>> import time
>>> type[time]


>>> time.__class__

5

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
28 của Python tuân theo Tiêu chuẩn IEEE 754 cho Số học dấu phẩy động, tiêu chuẩn này cố gắng biểu diễn tất cả các số dấu phẩy động trong 64 bit. Vì có vô số số dấu phẩy động nên bạn không thể biểu diễn tất cả chúng bằng một số bit hữu hạn

IEEE 754 quy định một hệ thống có mật độ số mà bạn có thể biểu diễn thay đổi. Bạn càng gần một, bạn càng có thể đại diện cho nhiều số hơn. Đối với các số lớn hơn, sẽ có nhiều khoảng cách hơn giữa các số mà bạn có thể biểu thị. Điều này có một số hậu quả khi bạn sử dụng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
28 để biểu thị thời gian

Xem xét

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
8. Mục đích chính của chức năng này là để đại diện cho thời gian thực tế ngay bây giờ. Nó thực hiện điều này dưới dạng số giây kể từ một thời điểm nhất định, được gọi là. Số được trả về bởi
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
8 khá lớn, có nghĩa là có ít số hơn và độ phân giải bị ảnh hưởng. Cụ thể,
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
8 không thể đo lường chênh lệch nano giây

>>>

>>> import time
>>> type[time]


>>> time.__class__

6

Một nano giây là một phần tỷ giây. Lưu ý rằng việc thêm một nano giây vào

>>> import time
>>> time.perf_counter[]
32311.48899951

>>> time.perf_counter[]  # A few seconds later
32315.261320793
12 không ảnh hưởng đến kết quả. Mặt khác,
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 sử dụng một số thời điểm không xác định làm kỷ nguyên của nó, cho phép nó hoạt động với số lượng nhỏ hơn và do đó có được độ phân giải tốt hơn

>>>

>>> import time
>>> type[time]


>>> time.__class__

7

Ở đây, bạn nhận thấy rằng việc thêm một nano giây vào

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
36 thực sự ảnh hưởng đến kết quả. Để biết thêm thông tin về cách làm việc với
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
8, hãy xem Hướng dẫn dành cho người mới bắt đầu về Mô-đun thời gian Python

Những thách thức với việc biểu diễn thời gian dưới dạng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
28 đã được nhiều người biết đến, vì vậy Python 3. 7 đã giới thiệu một tùy chọn mới. Mỗi hàm đo lường
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
4 hiện có một hàm
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
00 tương ứng trả về số nano giây dưới dạng
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
41 thay vì số giây dưới dạng
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
28. Chẳng hạn,
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
8 hiện có một bản sao nano giây có tên là
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
44

>>>

>>> import time
>>> type[time]


>>> time.__class__

8

Số nguyên không bị chặn trong Python, vì vậy điều này cho phép

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
44 đưa ra độ phân giải nano giây vĩnh viễn. Tương tự,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
01 là một biến thể nano giây của
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6

>>>

>>> import time
>>> type[time]


>>> time.__class__

9

Bởi vì

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 đã cung cấp độ phân giải nano giây nên có ít lợi thế hơn khi sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
01

Ghi chú.

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
01 chỉ khả dụng trong Python 3. 7 trở lên. Trong hướng dẫn này, bạn đã sử dụng
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 trong lớp học
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 của mình. Bằng cách đó, bạn cũng có thể sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 trên các phiên bản Python cũ hơn

Để biết thêm thông tin về các hàm

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
00 trong
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
4, hãy xem

Có hai chức năng trong

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
4 không đo thời gian ngủ. Đây là
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
7 và
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
9, hữu ích trong một số cài đặt. Tuy nhiên, đối với
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28, bạn thường muốn đo toàn bộ thời gian dành cho. Chức năng cuối cùng trong danh sách trên là
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
5. Cái tên ám chỉ chức năng này là một bộ đếm thời gian đơn điệu, là bộ đếm thời gian Python không bao giờ có thể di chuyển lùi

Tất cả các chức năng này đều đơn điệu ngoại trừ

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
8, có thể quay ngược lại nếu thời gian hệ thống được điều chỉnh. Trên một số hệ thống,
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
5 có cùng chức năng với
 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 và bạn có thể sử dụng chúng thay thế cho nhau. However, this is not always the case. Bạn có thể sử dụng
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
64 để biết thêm thông tin về chức năng hẹn giờ Python

>>>

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

0

Kết quả có thể khác trên hệ thống của bạn

PEP 418 mô tả một số lý do đằng sau việc giới thiệu các chức năng này. Nó bao gồm các mô tả ngắn sau đây

  •  1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main[]:
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter[]
     9    tutorial = feed.get_article[0]
    10    toc = time.perf_counter[]
    11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
    12
    13    print[tutorial]
    14
    15if __name__ == "__main__":
    16    main[]
    
    65. thời gian chờ và lập lịch trình, không bị ảnh hưởng bởi cập nhật đồng hồ hệ thống
  •  1# timer.py
     2
     3import time
     4
     5class TimerError[Exception]:
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__[self]:
    10        self._start_time = None
    11
    12    def start[self]:
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
    16
    17        self._start_time = time.perf_counter[]
    18
    19    def stop[self]:
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
    23
    24        elapsed_time = time.perf_counter[] - self._start_time
    25        self._start_time = None
    26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
    
    3. điểm chuẩn, đồng hồ chính xác nhất trong thời gian ngắn
  •  1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main[]:
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter[]
     9    tutorial = feed.get_article[0]
    10    toc = time.perf_counter[]
    11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
    12
    13    print[tutorial]
    14
    15if __name__ == "__main__":
    16    main[]
    
    67. lập hồ sơ, thời gian CPU của tiến trình []

Như bạn có thể thấy,

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
6 thường là lựa chọn tốt nhất cho bộ đếm thời gian Python của bạn

Loại bỏ các quảng cáo

Ước tính thời gian chạy với
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
69

Giả sử bạn đang cố gắng vắt kiệt phần hiệu suất cuối cùng ra khỏi mã của mình và bạn đang băn khoăn về cách hiệu quả nhất để chuyển đổi danh sách thành tập hợp. Bạn muốn so sánh bằng cách sử dụng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
70 và bộ chữ,
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
71. Bạn có thể sử dụng bộ đếm thời gian Python của mình cho việc này

>>>

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

1

Thử nghiệm này dường như chỉ ra rằng bộ chữ có thể nhanh hơn một chút. Tuy nhiên, những kết quả này khá không chắc chắn và nếu bạn chạy lại mã, bạn có thể nhận được kết quả rất khác. Đó là bởi vì bạn chỉ thử mã một lần. Chẳng hạn, bạn có thể gặp xui xẻo và chạy tập lệnh ngay khi máy tính của bạn đang bận rộn với các tác vụ khác

Cách tốt hơn là sử dụng thư viện chuẩn

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
69. Nó được thiết kế chính xác để đo thời gian thực thi của các đoạn mã nhỏ. Mặc dù bạn có thể nhập và gọi
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
73 từ Python như một chức năng thông thường, nhưng việc sử dụng giao diện dòng lệnh thường sẽ thuận tiện hơn. Bạn có thể tính thời gian cho hai biến thể như sau

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

2

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
69 tự động gọi mã của bạn nhiều lần để lấy trung bình các phép đo nhiễu. Kết quả từ
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
69 xác nhận rằng bộ chữ nhanh hơn
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
70

Ghi chú. Hãy cẩn thận khi bạn đang sử dụng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
69 trên mã có thể tải tệp xuống hoặc truy cập cơ sở dữ liệu. Vì
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
69 tự động gọi chương trình của bạn nhiều lần, bạn có thể vô tình gửi thư rác cho máy chủ bằng các yêu cầu

Cuối cùng, shell tương tác IPython và Jupyter Notebook có hỗ trợ thêm cho chức năng này với lệnh ma thuật

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
79

>>>

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

3

Một lần nữa, các phép đo chỉ ra rằng sử dụng một bộ chữ sẽ nhanh hơn. Trong Jupyter Notebooks, bạn cũng có thể sử dụng phép thuật ô

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
80 để đo thời gian chạy toàn bộ ô

Tìm nút cổ chai trong mã của bạn với Profilers

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
69 là lựa chọn tuyệt vời để đo điểm chuẩn cho một đoạn mã cụ thể. Tuy nhiên, sẽ rất cồng kềnh nếu sử dụng nó để kiểm tra tất cả các phần trong chương trình của bạn và xác định phần nào chiếm nhiều thời gian nhất. Thay vào đó, bạn có thể sử dụng một hồ sơ

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
82 là một hồ sơ mà bạn có thể truy cập bất cứ lúc nào từ thư viện tiêu chuẩn. Bạn có thể sử dụng nó theo nhiều cách, mặc dù cách đơn giản nhất là sử dụng nó như một công cụ dòng lệnh

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

4

Lệnh này chạy

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
10 với cấu hình được bật. Bạn lưu đầu ra từ
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
82 trong
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
85, như được chỉ định bởi tùy chọn
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
86. Dữ liệu đầu ra ở định dạng nhị phân cần một chương trình chuyên dụng để hiểu ý nghĩa của nó. Một lần nữa, Python có một tùy chọn ngay trong thư viện chuẩn. Chạy mô-đun trên tệp
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
88 của bạn sẽ mở trình duyệt thống kê hồ sơ tương tác

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

5

Để sử dụng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
87, bạn gõ lệnh tại dấu nhắc. Tại đây bạn có thể thấy hệ thống trợ giúp tích hợp. Thông thường, bạn sẽ sử dụng các lệnh
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
90 và
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
91. Để có được đầu ra sạch hơn,
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
92 có thể hữu ích

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

6

Đầu ra này cho thấy tổng thời gian chạy là 0. 586 giây. Nó cũng liệt kê mười chức năng mà mã của bạn dành phần lớn thời gian. Ở đây bạn đã sắp xếp theo thời gian tích lũy [_______28_______93], có nghĩa là mã của bạn tính thời gian khi hàm đã cho gọi một hàm khác

Bạn có thể thấy rằng mã của bạn hầu như dành toàn bộ thời gian bên trong mô-đun

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
94 và đặc biệt là bên trong
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
95. Mặc dù đây có thể là xác nhận hữu ích về những gì bạn đã biết, nhưng sẽ thú vị hơn khi tìm thấy mã của bạn thực sự dành thời gian ở đâu

Cột tổng thời gian [

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
96] cho biết lượng thời gian mã của bạn dành cho một chức năng, không bao gồm thời gian trong các chức năng phụ. Bạn có thể thấy rằng không có chức năng nào ở trên thực sự dành thời gian cho việc này. Để tìm nơi mã dành phần lớn thời gian, hãy đưa ra một lệnh
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
90 khác

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

7

Bây giờ bạn có thể thấy rằng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
10 thực sự dành phần lớn thời gian để làm việc với ổ cắm hoặc xử lý dữ liệu bên trong
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
99. Cái sau là một trong những phần phụ thuộc của Real Python Reader được sử dụng để phân tích nguồn cấp dữ liệu hướng dẫn

Bạn có thể sử dụng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
87 để biết phần nào mã của bạn dành phần lớn thời gian ở đâu và sau đó cố gắng tối ưu hóa bất kỳ tắc nghẽn nào bạn tìm thấy. Bạn cũng có thể sử dụng công cụ này để hiểu rõ hơn về cấu trúc mã của mình. Chẳng hạn, các lệnh
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
01 và
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
02 sẽ cho bạn biết hàm nào gọi và được gọi bởi một hàm đã cho

Bạn cũng có thể điều tra các chức năng nhất định. Kiểm tra xem có bao nhiêu chi phí mà

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 gây ra bằng cách lọc kết quả bằng cụm từ
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
04

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

8

May mắn thay,

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
28 chỉ gây ra chi phí tối thiểu. Sử dụng
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
06 để thoát khỏi trình duyệt
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
87 khi bạn điều tra xong

Để có giao diện mạnh mẽ hơn vào dữ liệu hồ sơ, hãy xem KCacheGrind. Nó sử dụng định dạng dữ liệu riêng, nhưng bạn có thể chuyển đổi dữ liệu từ

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
82 bằng cách sử dụng
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
09

>>> type[3]


>>> type[None]


>>> type[print]


>>> type[type]

9

Lệnh này sẽ chuyển đổi

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
85 và mở KCacheGrind để phân tích dữ liệu

The last option that you’ll try here for timing your code is

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
11.
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
82 có thể cho bạn biết chức năng nào mà mã của bạn dành nhiều thời gian nhất, nhưng nó sẽ không cung cấp cho bạn thông tin chi tiết về dòng nào bên trong chức năng đó là chậm nhất. Đó là nơi mà
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
11 có thể giúp bạn

Ghi chú. Bạn cũng có thể định cấu hình mức tiêu thụ bộ nhớ của mã của mình. Điều này nằm ngoài phạm vi của hướng dẫn này. Tuy nhiên, bạn có thể xem

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
14 nếu bạn cần theo dõi mức tiêu thụ bộ nhớ của các chương trình của mình

Lưu ý rằng cấu hình dòng cần có thời gian và thêm một chút chi phí hợp lý vào thời gian chạy của bạn. Một quy trình công việc bình thường trước tiên là sử dụng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main[]:
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter[]
 9    tutorial = feed.get_article[0]
10    toc = time.perf_counter[]
11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
12
13    print[tutorial]
14
15if __name__ == "__main__":
16    main[]
82 để xác định chức năng nào cần điều tra và sau đó chạy
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
11 trên các chức năng đó.
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
11 không phải là một phần của thư viện tiêu chuẩn, vì vậy trước tiên bạn nên làm theo hướng dẫn để thiết lập

Trước khi bạn chạy trình cấu hình, bạn cần cho nó biết chức năng nào cần cấu hình. Bạn làm điều này bằng cách thêm một trình trang trí

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
18 bên trong mã nguồn của bạn. Ví dụ: với hồ sơ
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
19, bạn thêm phần sau vào bên trong
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main[]:
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article[0]
 8    print[tutorial]
 9
10if __name__ == "__main__":
11    main[]
40

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
0

Lưu ý rằng bạn không nhập

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
21 ở bất cứ đâu. Thay vào đó, nó sẽ tự động được thêm vào không gian tên chung khi bạn chạy trình lược tả. Tuy nhiên, bạn cần xóa dòng này khi hoàn tất hồ sơ. Nếu không, bạn sẽ nhận được một
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
22

Tiếp theo, chạy trình lược tả bằng cách sử dụng

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
23, đây là một phần của gói
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
11

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
1

Lệnh này tự động lưu dữ liệu hồ sơ trong một tệp có tên

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
25. Bạn có thể xem kết quả bằng cách sử dụng _______ 33 _______ 11

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
2

Đầu tiên, lưu ý rằng đơn vị thời gian trong báo cáo này là micro giây [

$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
27]. Thông thường, số dễ truy cập nhất để xem xét là
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
28, cho bạn biết tỷ lệ phần trăm tổng thời gian mã của bạn sử dụng bên trong một hàm tại mỗi dòng. Trong ví dụ này, bạn có thể thấy rằng mã của bạn dành gần 70 phần trăm thời gian cho dòng 47, đây là dòng định dạng và in kết quả của bộ đếm thời gian

Phần kết luận

Trong hướng dẫn này, bạn đã thử một số cách tiếp cận khác nhau để thêm bộ hẹn giờ Python vào mã của mình

  • Bạn đã sử dụng một lớp để giữ trạng thái và thêm giao diện thân thiện với người dùng. Các lớp học rất linh hoạt và việc sử dụng trực tiếp

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    28 sẽ cho bạn toàn quyền kiểm soát cách thức và thời điểm gọi bộ đếm thời gian

  • Bạn đã sử dụng trình quản lý bối cảnh để thêm các tính năng vào một khối mã và, nếu cần, để dọn dẹp sau đó. Trình quản lý ngữ cảnh rất dễ sử dụng và việc thêm

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ .. ]
    
    30 có thể giúp bạn phân biệt rõ ràng hơn mã của mình một cách trực quan

  • Bạn đã sử dụng một trình trang trí để thêm hành vi vào một chức năng. Trình trang trí ngắn gọn và hấp dẫn, đồng thời sử dụng

     1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main[]:
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter[]
     9    tutorial = feed.get_article[0]
    10    toc = time.perf_counter[]
    11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
    12
    13    print[tutorial]
    14
    15if __name__ == "__main__":
    16    main[]
    
    09 là một cách nhanh chóng để theo dõi thời gian chạy mã của bạn

Bạn cũng đã biết lý do tại sao bạn nên ưu tiên

 1# timer.py
 2
 3import time
 4
 5class TimerError[Exception]:
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__[self]:
10        self._start_time = None
11
12    def start[self]:
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError[f"Timer is running. Use .stop[] to stop it"]
16
17        self._start_time = time.perf_counter[]
18
19    def stop[self]:
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError[f"Timer is not running. Use .start[] to start it"]
23
24        elapsed_time = time.perf_counter[] - self._start_time
25        self._start_time = None
26        print[f"Elapsed time: {elapsed_time:0.4f} seconds"]
3 hơn
$ python latest_tutorial.py
Downloaded the tutorial in 0.6721 seconds
# Python Timer Functions: Three Ways to Monitor Your Code

[ .. ]
33 khi đo điểm chuẩn cho mã, cũng như những lựa chọn thay thế khác hữu ích khi bạn tối ưu hóa mã của mình

Bây giờ bạn có thể thêm các hàm hẹn giờ Python vào mã của riêng mình. Theo dõi chương trình của bạn chạy nhanh như thế nào trong nhật ký sẽ giúp bạn theo dõi các tập lệnh của mình. Bạn có ý tưởng nào cho các trường hợp sử dụng khác trong đó các lớp, trình quản lý ngữ cảnh và trình trang trí kết hợp tốt với nhau không?

Tài nguyên

Để tìm hiểu sâu hơn về các chức năng hẹn giờ của Python, hãy xem các tài nguyên này

  •  1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main[]:
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article[0]
     8    print[tutorial]
     9
    10if __name__ == "__main__":
    11    main[]
    
    29 là bộ đếm thời gian Python có sẵn trên PyPI
  • là một bộ đếm hiệu suất cho thời gian chính xác
  •  1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main[]:
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter[]
     9    tutorial = feed.get_article[0]
    10    toc = time.perf_counter[]
    11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
    12
    13    print[tutorial]
    14
    15if __name__ == "__main__":
    16    main[]
    
    69 là một công cụ để so sánh thời gian chạy của các đoạn mã
  •  1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main[]:
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter[]
     9    tutorial = feed.get_article[0]
    10    toc = time.perf_counter[]
    11    print[f"Downloaded the tutorial in {toc - tic:0.4f} seconds"]
    12
    13    print[tutorial]
    14
    15if __name__ == "__main__":
    16    main[]
    
    82 là một công cụ hồ sơ để tìm ra các nút thắt cổ chai trong các tập lệnh và chương trình
  • là một công cụ dòng lệnh để xem dữ liệu hồ sơ
  • KCachegrind là một GUI để xem dữ liệu hồ sơ
  • $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ .. ]
    
    11 là một hồ sơ để đo các dòng mã riêng lẻ
  • $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ .. ]
    
    14 là một hồ sơ để theo dõi việc sử dụng bộ nhớ

Đánh dấu là đã hoàn thành

🐍 Thủ thuật Python 💌

Nhận một Thủ thuật Python ngắn và hấp dẫn được gửi đến hộp thư đến của bạn vài ngày một lần. Không có thư rác bao giờ. Hủy đăng ký bất cứ lúc nào. Được quản lý bởi nhóm Real Python

Gửi cho tôi thủ thuật Python »

Giới thiệu về Geir Arne Hjelle

Geir Arne là một Pythonista cuồng nhiệt và là thành viên của nhóm hướng dẫn Real Python

» Thông tin thêm về Geir Arne

Mỗi hướng dẫn tại Real Python được tạo bởi một nhóm các nhà phát triển để nó đáp ứng các tiêu chuẩn chất lượng cao của chúng tôi. Các thành viên trong nhóm đã làm việc trong hướng dẫn này là

Aldren

Đan

Jaya

Joanna

kate

Mike

Philipp

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas

Nâng cao kỹ năng Python của bạn »

Chuyên gia Kỹ năng Python trong thế giới thực
With Unlimited Access to Real Python

Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn, khóa học video thực hành và cộng đồng Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Bạn nghĩ sao?

Đánh giá bài viết này

Tweet Chia sẻ Chia sẻ Email

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know

Mẹo bình luận. The most useful comments are those written with the goal of learning from or helping out other students. và nhận câu trả lời cho các câu hỏi phổ biến trong cổng thông tin hỗ trợ của chúng tôi

Can you code a timer in Python?

If you're programming in Python, you're in luck. Ngôn ngữ cung cấp cho bạn các công cụ để xây dựng bộ hẹn giờ của riêng bạn . Một chương trình hẹn giờ có thể hữu ích không chỉ để theo dõi thời gian của riêng bạn mà còn đo thời gian chạy chương trình Python của bạn.

How does Python calculate timer?

Để tính thời gian thực thi mã, mô-đun thời gian có thể được sử dụng. .
Lưu dấu thời gian ở đầu mã bắt đầu sử dụng time[]
Lưu dấu thời gian ở cuối mã
Find the difference between the end and start, which gives the execution time

Chủ Đề