Làm cách nào để tạo đồng hồ bấm giờ trong Python?

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

In this tutorial, you’ll learn how to 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"]
    
    3 to measure time in Python
  • Classes to keep state
  • Context managers to work with a block of code
  • Decorators to customize a function

You’ll also gain background knowledge into how classes, context managers, and decorators work. As you explore examples of each concept, you’ll be inspired to use one or several of them in your code, for timing code execution, as well as in other applications. Each method has its advantages, and you’ll learn which to use depending on the situation. Plus, you’ll have a working Python timer that you can use to monitor your programs

Decorators Q&A Transcript. Click here to get access to a 25-page chat log from our Python decorators Q&A session in the Real Python Community Slack where we discussed common decorator questions

Python Timers

First, you’ll take a look at some example code that you’ll use throughout the tutorial. Later, you’ll add a Python timer to this code to monitor its performance. You’ll also learn some of the simplest ways to measure the running time of this example

Remove ads

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

If you check out the built-in

 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 in Python, then you’ll notice several functions that can measure time

Python 3. 7 introduced several new functions, like , as well as nanosecond versions of all the functions above, named with an

 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 suffix. For example, is the nanosecond version of
 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’ll learn more about these functions later. 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. Again, this is a performance counter that’s well-suited for timing parts of your code

 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

Ghi chú. Ở dòng 11,

 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 trước chuỗi cho biết đây là chuỗi f, đây là cách thuận tiện để định dạng chuỗi vă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[]
24 là một công cụ xác định định dạng cho biết số,
 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, phải được in dưới dạng số thập phân có bốn số thập phân

Để biết thêm thông tin về chuỗi f, hãy xem Chuỗi f của Python 3. Cú pháp định dạng chuỗi được cải thiện

Bây giờ, khi bạn chạy ví dụ, bạn sẽ thấy thời gian đã trôi qua trước phần hướng dẫn

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

[ .. ]

Đó là nó. Bạn đã nắm được kiến ​​thức cơ bản về định thời gian cho mã Python của riêng mình. Trong phần còn lại của hướng dẫn, bạn sẽ học cách gói bộ đếm thời gian Python vào một lớp, trình quản lý ngữ cảnh và trình trang trí để làm cho nó nhất quán và thuận tiện hơn khi sử dụng

Remove ads

Lớp hẹn giờ Python

Nhìn lại cách bạn đã thêm bộ đếm thời gian Python vào ví dụ trên. 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. Để biết thêm thông tin, hãy xem Ngoại lệ Python. 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. Once the timer is running,
 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 keeps track of when the timer started

Note. The underscore [

 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] prefix 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[]
37 is a Python convention. It signals 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[]
37 is an internal attribute that users of 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[]
28 class shouldn’t manipulate

When you call

 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 to start a new Python timer, you first check that the timer isn’t already running. Then you store the current value of
 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 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[]
37

On the other hand, when you call

 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 first check that the Python timer is running. If it is, then you calculate the elapsed time as the difference between the current value of
 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 and the one that you stored 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[]
37. Finally, you reset
 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 so that the timer can be restarted, and print the elapsed time

Here’s how 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[]
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

Compare this to the where you used

 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 directly. The structure of the code is fairly similar, but now the code is clearer, and this is one of the benefits of using classes. By carefully choosing your class, method, and attribute names, you can make your code very descriptive

Remove ads

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

Lưu ý rằng mã rất giống với mã bạn đã sử dụng trước đó. 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

Dưới đây là hai ví dụ cho thấy chức năng mới đang hoạ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[]
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. Bạn sẽ thêm một chút chức năng dưới dạng bộ hẹn giờ được đặt tên với một từ điển theo dõi mọi bộ hẹn giờ Python trong mã của bạn

Giả sử rằng bạn đang 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[]
10 thành một tập 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/ »

* * *
01 để tải xuống và in mười hướng dẫn mới nhất từ ​​Real Python. Sau đây là một thực hiện có 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[]
8

Đoạn mã lặp qua các số từ 0 đến 9 và sử dụng các số đó làm đối số bù cho

$ 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. Khi bạn chạy tập lệnh, bạn sẽ in rất nhiều thông tin vào bảng điều khiển của mì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[]
9

Một vấn đề tế nhị với đoạn mã này là bạn đang đo không chỉ thời gian cần thiết để tải xuống các hướng dẫn mà còn cả thời gian Python dành để in các hướng dẫn lên màn hình của bạn. Điều này có thể không quan trọng vì thời gian dành cho in ấn không đáng kể so với thời gian tải xuống. Tuy nhiên, sẽ rất tốt nếu có một cách để tính thời gian chính xác cho những gì bạn đang theo đuổi trong những tình huống như thế này

Ghi chú. Thời gian tải xuống mười hướng dẫn bằng thời gian tải xuống một hướng dẫn. Đây không phải là một lỗi trong mã của bạn. Thay vào đó,

 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 lưu trữ nguồn cấp dữ liệu Python thực trong lần đầu tiên ___21_______04 được gọi và sử dụng lại thông tin trong các lần gọi sau

Có một số cách mà bạn có thể giải quyết vấn đề này mà không thay đổi cách triển khai hiện tại 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/ »

* * *
05 Tuy nhiên, việc hỗ trợ trường hợp sử dụng này sẽ khá hữu ích và bạn có thể thực hiện điều đó chỉ với một vài dòng mã

Trước tiên, bạn sẽ giới thiệu một từ điển có tên 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/ »

* * *
06 dưới dạng một biến lớp 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ó nghĩa là tất cả các phiên 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[]
28 sẽ chia sẻ nó. Bạn triển khai nó bằng cách định nghĩa nó bên ngoài bất kỳ phương thức 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/ »

* * *
0

Các biến lớp có thể được truy cập trực tiếp trên lớp hoặc thông qua một thể hiện của lớ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/ »

* * *
1

Trong cả hai trường hợp, mã trả về cùng một từ điển lớp trống

Tiếp theo, bạn sẽ thêm tên tùy chọn vào bộ đếm thời gian Python của mình. 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. Chúng cung cấp một số tiện ích cho các lớp của bạn, bao gồm một chuỗi biểu diễn nhiều thông tin hơn

Ghi chú. Các lớp dữ liệu chỉ được bao gồm trong Python cho phiên bản 3. 7 trở lên. Tuy nhiên, có sẵn một backport trên PyPI cho Python 3. 6

Bạn có thể 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 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

Xem Các lớp dữ liệu trong Python 3. 7+ [Hướng dẫn] để biết thêm thông tin

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. Bạn sẽ tìm hiểu thêm về người trang trí. Hiện tại, bạn có thể coi đây là một ký hiệu cho Python biế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à một lớp dữ liệu

$ 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

    $ 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 đặc biệt cho bất kỳ lần 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

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 mới của bạn hoạt động giống như lớp thông thường trước đó của bạn, ngoại trừ việc bây giờ nó có một biểu diễn đẹ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/ »

* * *
9

Bây giờ bạn đã có một phiên bản khá gọn gàng 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 nhất quán, linh hoạt, thuận tiện và nhiều thông tin. Bạn cũng có thể áp dụng nhiều cải tiến mà bạn đã thực hiện trong phần này cho các loại lớp khác trong dự án của mình

Trước khi kết thúc phần này, hãy xem lại mã nguồn hoàn chỉnh 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 như hiện tại. Bạn sẽ nhận thấy việc thêm các gợi ý loại vào mã để có thêm tài liệu

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

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

Sử dụng một lớp để tạo bộ đếm thời gian Python có một số lợi ích

  • khả năng đọc. Mã của bạn sẽ đọc tự nhiên hơn nếu bạn cẩn thận chọn tên lớp và phương thức
  • Tính nhất quán. Mã của bạn sẽ dễ sử dụng hơn nếu bạn gói gọn các thuộc tính và hành vi thành các thuộc tính và phương thức
  • Uyển chuyển. 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

Remove ads

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 một chặng đường dài. So với , mã của bạn đã trở nên khá mạnh mẽ. However, there’s still a bit of boilerplate code necessary to use your
 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. Đầ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ý ngữ 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ý bối 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ý ngữ 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 đây tiết lộ 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ý ngữ 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ý bối 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ý bối cảnh vì nó triển khai giao thức quản lý bối 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

Trước tiên, hãy lưu ý 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 được gọi trước khi bạn làm công việc, trong 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/ »

* * *
72 được gọi sau. 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, hãy 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ý bối 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 ____21_______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. If you want to dive deeper, then check out

$ 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 in the standard library. 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

Remove ads

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
$ 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 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ị hỏng. 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

Remove ads

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í. Decorators are powerful constructs that you use to modify the behavior of functions and classes. 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 gian. Để đượ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. Nói cách khác, các hàm có thể được gán cho các biến và được sử dụng làm đối số cho các hàm khác, giống như bất kỳ đối tượng nào khác. Đ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 mà
    >>> 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ế một chức năng này bằng một chức năng khác một cách hiệu quả nên chúng tạo ra một vấn đề 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. This will also replace the name, , and other metadata. 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

Remove ads

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 bản thiết kế ở 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

Remove ads

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

The location of the elapsed time output is a telltale sign that your code is considering the time it takes to print as well. 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

Tuy nhiên, trình trang trí không linh hoạt như trình quản lý ngữ cảnh. 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

>>> ______37_______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

Remove ads

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 lắm

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 tế, 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ố chức năng 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ả.
 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, on the other hand, uses some undefined point in time as its epoch, allowing it to work with smaller numbers and therefore obtain a better resolution

>>>

>>> 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

Các 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. Tuy nhiên, đây không phải là luôn luôn như vậy. 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

Remove ads

Ướ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 hàm 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, nê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, trình bao 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ộ ô

Finding Bottlenecks in Your Code With 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ó đầu ra sạch hơn, có thể hữu í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[]
92

>>> 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 [_______27_______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

Tùy chọn cuối cùng mà bạn sẽ thử ở đây để định thời gian cho mã của mình là

$ 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. Quy trình làm việc thông 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

This command automatically saves the profiler data in a file called

$ 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 những kết quả đó 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

[ .. ]
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 mã, cũng như những lựa chọn thay thế nào 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 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

Bậc thầy Kỹ năng Python trong thế giới thực Với quyền truy cập không giới hạn vào Python thực

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

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

Chuyên gia Kỹ năng Python trong thế giới thực
Với quyền truy cập không giới hạn vào Python thực

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

Bài học số 1 hoặc điều yêu thích mà bạn đã học được là gì?

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

Làm cách nào để tạo bộ đếm thời gian trong Python?

Làm theo các bước bên dưới để tạo đồng hồ đếm ngược. .
Step 1. Import the time module
Bước 2. Sau đó yêu cầu người dùng nhập thời lượng đếm ngược tính bằng giây
Step 3. This value is sent as a parameter 't' to the user-defined function countdown[]. .
Bước 4. In this function, a while loop runs until time becomes 0

Có một bộ đếm thời gian trong python?

A timer in Python is a time-tracking program . Python developers can create timers with the help of Python's time modules. There are two basic types of timers. timers that count up and those that count down.

How to use clock in Python?

clock[] method of time module in Python is used to get the current processor time as a floating point number expressed in seconds . As, Most of the functions defined in time module call corresponding C library function. thời gian. clock[] method also call C library function of the same name to get the result.

Chủ Đề