Hướng dẫn can you make a timer in python? - bạn có thể hẹn giờ trong python không?

Cải thiện bài viết

Show

Lưu bài viết

  • Đọc
  • Bàn luận
  • Cải thiện bài viết

    Lưu bài viết

    Đọc

    Bàn luận

    Trong bài viết này, chúng ta sẽ xem cách tạo bộ đếm thời gian đếm ngược bằng Python. Mã sẽ lấy đầu vào từ người dùng về độ dài của đếm ngược tính bằng giây. Sau đó, việc đếm ngược sẽ bắt đầu trên màn hình của định dạng ‘phút: giây. Chúng tôi sẽ sử dụng mô -đun thời gian ở đây. sleep() function. Follow the below steps to create a countdown timer:

    • Cách tiếp cận Import the time module.
    • Trong dự án này, chúng tôi sẽ sử dụng mô -đun thời gian và hàm Sleep () của nó. Thực hiện theo các bước dưới đây để tạo bộ đếm thời gian đếm ngược: Then ask the user to input the length of the countdown in seconds.
    • Bước 1: Nhập mô -đun thời gian. This value is sent as a parameter ‘t’ to the user-defined function countdown(). Any variable read using the input function is a string. So, convert this parameter to ‘int’ as it is of string type.
    • Bước 2: Sau đó, yêu cầu người dùng nhập chiều dài đếm ngược tính bằng giây. In this function, a while loop runs until time becomes 0.
    • Bước 3: Giá trị này được gửi dưới dạng tham số ‘T, đến Chức năng do người dùng xác định (). Bất kỳ biến nào đọc bằng hàm đầu vào là một chuỗi. Vì vậy, hãy chuyển đổi tham số này thành ‘int, vì nó thuộc loại chuỗi. Use divmod() to calculate the number of minutes and seconds. You can read more about it here.
    • Bước 4: Trong hàm này, vòng lặp trong thời gian chạy cho đến khi thời gian trở thành 0. Now print the minutes and seconds on the screen using the variable timeformat.
    • Bước 5: Sử dụng divmod () để tính toán số phút và giây. Bạn có thể đọc thêm về nó ở đây. Using end = ‘\r’ we force the cursor to go back to the start of the screen (carriage return) so that the next line printed will overwrite the previous one.
    • Bước 6: Bây giờ in số phút và giây trên màn hình bằng cách sử dụng thời gian thay đổi. The time.sleep()is used to make the code wait for one sec.
    • Bước 7: Sử dụng end = ‘\ r, chúng tôi buộc con trỏ phải quay lại đầu màn hình (trả về vận chuyển) để dòng tiếp theo được in sẽ ghi đè lên cái trước. Now decrement time so that the while loop can converge.
    • Bước 8: Thời gian.s ngủ () được sử dụng để làm cho mã chờ một giây. After the completion of the loop, we will print “Fire in the hole” to signify the end of the countdown.

    Bước 9: Bây giờ thời gian giảm để vòng lặp trong khi có thể hội tụ.

    Python3

    Bước 10: Sau khi hoàn thành vòng lặp, chúng tôi sẽ in lửa trong lỗ hổng để biểu thị sự kết thúc của đếm ngược.

    Dưới đây là việc thực hiện phương pháp trê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")
    
    0
     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

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

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

     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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    13
     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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    15
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    03

     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
     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
     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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    022

     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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    05
     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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    07
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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

     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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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()
    
    29
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    03

     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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    18
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    19
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    03

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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

    Output:  
     

    https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200729151851/python-countdown-timer.webm

    Trong khi nhiều nhà phát triển nhận ra Python là ngôn ngữ lập trình hiệu quả, các chương trình Python thuần túy có thể chạy chậm hơn so với các đối tác của họ 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 mức độ nhanh chóng của các chương trình của bạn.Python timer to monitor how quickly your programs are running.

    Trong hướng dẫn này, 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()
      
      40 để đo thời gian trong Python
      to measure time in Python
    • Các lớp học để giữ trạng thái to keep state
    • Người quản lý bối cảnh làm việc với một khối mã to work with a block of code
    • Người trang trí để tùy chỉnh một chức năng to customize a function

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

    Đồng hồ hẹn giờ

    Đầu tiên, bạn sẽ xem xét một số mã ví dụ mà bạn sẽ sử dụng trong suốt hướng dẫn. Sau đó, bạn sẽ thêm một bộ đếm thời gian python vào mã này để theo dõi hiệu suất của nó. Bạn cũng sẽ học một số cách đơn giản nhất để đo thời gian chạy của ví dụ này.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.

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

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

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

    •  1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """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
    •  1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """Download and print the latest tutorial from Real Python"""
       7    tutorial = feed.get_article(0)
       8    print(tutorial)
       9
      10if __name__ == "__main__":
      11    main()
      
      43
    •  1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """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
    •  1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """Download and print the latest tutorial from Real Python"""
       7    tutorial = feed.get_article(0)
       8    print(tutorial)
       9
      10if __name__ == "__main__":
      11    main()
      
      45

    Python 3.7 đã giới thiệu một số chức năng mới, 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()
    
    46, cũng như các phiên bản nano giây của tất cả các chức năng ở trên, được đặt tên với hậu tố
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    47. 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()
    
    48 là phiên bản nano giây 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()
    
    43. Bạn sẽ tìm hiểu thêm về các chức năng này sau này. Hiện tại, lưu ý những gì tài liệu phải nói 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()
    
    43: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()
    
    47 suffix. For example,
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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 is the nanosecond 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()
    
    43. You’ll learn more about these functions later. For now, note what the documentation has to say 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()
    
    43:

    Trả về giá trị (tính bằng giây phân đoạn) của bộ đếm hiệu suất, tức là đồng hồ có độ phân giải cao nhất để đo thời lượng ngắn. (Nguồn)

    Đầu tiên, bạn sẽ 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()
    
    43 để tạo bộ hẹn giờ Python. Sau đó, bạn sẽ so sánh điều này với các chức năng hẹn giờ Python khác và tìm hiểu lý do tại sao
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    43 thường là lựa chọn tốt nhất.

    Ví dụ: Tải xuống hướng dẫn

    Để so sánh tốt hơn các cách khác nhau mà bạn có thể thêm bộ hẹn giờ Python vào mã của mình, bạn sẽ áp dụng các chức năng hẹn giờ Python khác nhau vào cùng một ví dụ về mã trong suốt hướng dẫn này. Nếu bạn đã có mã mà bạn muốn đo, thì hãy tự do làm theo các ví dụ với điều đó.

    Ví dụ mà bạn sẽ sử dụng trong hướng dẫn này là một hàm ngắn sử dụng 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()
    
    53 để tải xuống các hướng dẫn mới nhất có sẵn tại đây trên Real Python. Để tìm hiểu thêm về đầu đọc Python thực sự và cách thức hoạt động, hãy xem cách xuất bản gói Python nguồn mở lên PYPI. Bạn có thể cài đặ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()
    
    53 trên hệ thống của mình 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()
    
    55:

    $ python -m pip install realpython-reader
    

    Sau đó, bạn có thể nhập gói dưới 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()
    
    56.

    Bạn sẽ lưu trữ ví dụ trong một 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()
    
    57. Mã này bao gồm một chức năng tải xuống và in hướng dẫn mới nhất từ ​​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()
    
    53 xử lý hầu hết các công việc khó khăn:

    • Dòng 3 Nhập khẩ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()
      
      59 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()
      
      53. Mô -đun này chứa chức năng để tải xuống các hướng dẫn từ nguồn cấp dữ liệu Python thực sự.
      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()
      
      59 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()
      
      53. This module contains functionality for downloading tutorials from the Real Python feed.
    • Dòng 7 Tải xuống hướng dẫn mới nhất từ ​​Real Python. 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()
      
      61 là một phần bù, 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()
      
      61 có nghĩa là hướng dẫn gần đây nhấ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()
      
      19 là hướng dẫn trước đây, v.v.
      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()
      
      61 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()
      
      61 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()
      
      19 is the previous tutorial, and so on.
    • Dòng 8 in hướng dẫn cho bảng điều khiển. prints the tutorial to the console.
    • Dòng 11 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()
      
      64 Khi bạn chạy tập lệnh.
      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()
      
      64 when you run the script.

    Khi bạn chạy ví dụ này, đầu ra của bạn thường sẽ trông giống như thế 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 https://realpython.com/python-timer/ »
    
    * * *
    

    Mã có thể mất một chút thời gian để chạy tùy thuộc vào mạng của bạn, vì vậy bạn có thể muốn sử dụng bộ hẹn giờ Python để theo dõi hiệu suất của tập lệnh.

    Bộ đếm thời gian Python đầu tiên của bạn

    Bây giờ, bạn sẽ thêm một bộ đếm thời gian trăn trần vào ví dụ 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()
    
    40. Một lần nữa, đây là một bộ đếm hiệu suất phù hợp với các phần thời gian của mã của bạn.performance counter that’s well-suited for timing parts of your 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()
    
    43 đo thời gian tính bằng vài giây từ một số thời điểm không xác định, điều đó có nghĩa là giá trị trả lại của một cuộc gọi cho chức năng không hữu ích. Tuy nhiên, khi bạn nhìn vào sự khác biệt giữa hai cuộc gọi đế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()
    
    43, bạn có thể tìm ra bao nhiêu giây trôi qua giữa hai cuộc gọi:

    >>>

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    

    Trong ví dụ này, bạn đã thực hiện hai cuộc gọi đế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()
    
    43 cách nhau gần 4 giây. Bạn có thể xác nhận điều này bằng cách tính toán chênh lệch giữa hai đầu ra: 32315.26 - 32311,49 = 3,77.

    Bây giờ bạn có thể thêm bộ hẹn giờ Python vào mã ví dụ:

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

    Lưu ý rằng bạn gọi

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    43 cả trước và sau khi tải xuống hướng dẫn. Sau đó, bạn in thời gian để tải xuống hướng dẫn bằng cách tính toán sự khác biệt giữa hai cuộc gọi.

    Bây giờ, khi bạn chạy ví dụ, bạn sẽ thấy thời gian trôi qua trước 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 đã đề cập đến những điều cơ bản về thời gian của mã Python của riêng bạn. Trong phần còn lại của hướng dẫn, bạn sẽ tìm hiểu làm thế nào bạn có thể bọc một bộ đếm thời gian python vào một lớp học, một người quản lý bối cảnh và một người trang trí để làm cho nó phù hợp và thuận tiện hơn để sử dụng.

    Lớp học hẹn giờ Python

    Nhìn lại cách bạn đã thêm bộ hẹn giờ python vào ví dụ trên. Lưu ý rằng bạn cần ít nhất một biế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()
    
    70) để lưu trữ trạng thái của bộ hẹn giờ Python trước khi bạn tải xuống hướng dẫn. Sau khi nghiên cứu mã một chút, bạn cũng có thể lưu ý rằng ba dòng được tô sáng chỉ được thêm vào cho mục đích thời gian! Bây giờ, bạn sẽ tạo ra một lớp giống như các cuộc gọi hướng dẫn của bạn đế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()
    
    43, nhưng theo cách dễ đọc và nhất quán hơn.

    Trong suốt hướng dẫn này, bạn sẽ tạo và cập nhậ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()
    
    72, một lớp mà bạn có thể sử dụng để thời gian mã của mình theo nhiều cách khác nhau. Mã cuối cùng với một số tính năng bổ sung cũng có sẵn trên PYPI dưới 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()
    
    73. Bạn có thể cài đặt nó trên hệ thống của mình như vậy:

    $ python -m pip install codetiming
    

    Bạn có thể tìm thêm thông tin 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 sau này trong hướng dẫn này, trong phần có tên là mã hẹn giờ Python.

    Hiểu các lớp học trong Python

    Các lớp là các khối xây dựng chính của lập trình hướng đối tượng. Một lớp về cơ bản là một mẫu mà bạn có thể sử dụng để tạo các đối tượng. Trong khi Python không buộc bạn lập trình theo cách hướng đối tượng, các lớp học ở khắp mọi nơi trong ngôn ngữ. Để có bằng chứng nhanh, điều tra mô -đun

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

    >>>

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    

    Trong ví dụ này, bạn đã thực hiện hai cuộc gọi đế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()
    
    43 cách nhau gần 4 giây. Bạn có thể xác nhận điều này bằng cách tính toán chênh lệch giữa hai đầu ra: 32315.26 - 32311,49 = 3,77.

    >>>

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    

    Trong ví dụ này, bạn đã thực hiện hai cuộc gọi đế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()
    
    43 cách nhau gần 4 giây. Bạn có thể xác nhận điều này bằng cách tính toán chênh lệch giữa hai đầu ra: 32315.26 - 32311,49 = 3,77.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.

    Tạo lớp hẹn giờ Python

    Các lớp học tốt cho trạng thái theo dõi. Trong một 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()
    
    72, bạn muốn theo dõi thời điểm hẹn giờ bắt đầu và thời gian trôi qua kể từ đó. Đối với lần thực hiện đầu tiê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()
    
    72, bạn sẽ thêm thuộc tí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()
    
    81, cũng như các phương thứ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()
    
    82 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()
    
    83. Thêm mã sau 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()
    
    84: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()
    
    72 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()
    
    72, 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()
    
    81 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()
    
    82 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()
    
    83 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()
    
    84:

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

    Một vài điều khác nhau đang xảy ra ở đây, vì vậy hãy dành một chút thời gian để đi qua mã từng bước.

    Trong dòng 5, bạn xác định một 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()
    
    85. Ký hiệ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()
    
    86 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()
    
    85 kế thừa từ một lớp khác được gọi 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()
    
    88. Python sử dụng lớp tích hợp này để xử lý lỗi. Bạn không cần thêm bất kỳ thuộc tính hoặc phương thức nào 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()
    
    85, nhưng có lỗi tùy chỉnh sẽ cho bạn linh hoạt hơn để xử lý các vấn đề 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()
    
    72. Để biết thêm thông tin, hãy xem các ngoại lệ Python: Giới thiệu.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()
    
    88. 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()
    
    85, 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()
    
    72. For more information, check out Python Exceptions: An Introduction.

    Định nghĩa 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()
    
    72 tự bắt đầu trên dòng 8. Khi bạn lần đầu tiên tạo hoặc khởi tạo một đối tượng từ một lớp, mã của bạn gọi phương thức đặc biệ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()
    
    92. Trong phiên bản đầu tiê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()
    
    72, bạn chỉ khởi tạo thuộc tí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()
    
    81 mà bạn sẽ sử dụng để theo dõi trạng thái của bộ đếm thời gian Python của mình. Nó có giá 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()
    
    95 khi bộ đếm thời gian chạy. Khi bộ hẹn giờ đang chạy,
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    81 theo dõi khi bộ hẹn giờ bắt đầu.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()
    
    92. 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()
    
    72, 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()
    
    81 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()
    
    95 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()
    
    81 keeps track of when the timer started.

    Khi bạn gọi

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    82 để bắt đầu bộ đếm thời gian Python mới, trước tiên bạn sẽ kiểm tra xem bộ đếm thời gian có đang chạy không. Sau đó, bạn lưu trữ giá trị hiện tại 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()
    
    43 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()
    
    81.

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

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    83, trước tiên bạn kiểm tra xem bộ đếm thời gian Python có đang chạy không. Nếu có, thì bạn tính thời gian trôi qua là chênh lệch giữa giá trị hiện tại của
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    43 và giá trị mà bạn lưu trữ trong
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    81. Cuối cùng, bạn đặt lại
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    81 để bộ hẹn giờ có thể được khởi động lại và in thời gian trôi qua.

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

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

    >>>

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

    So sánh điều này với ví dụ trước đó mà bạn đã 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()
    
    43. Cấu trúc của mã khá giống nhau, nhưng bây giờ mã rõ ràng hơn và đây là một trong những lợi ích của việc sử dụng các lớp. Bằng cách chọn cẩn thận lớp, phương thức và tên thuộc tính của bạn, bạn có thể làm cho mã của mình rất mô tả!

    Sử dụng lớp hẹn giờ Python

    Bây giờ áp 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()
    
    72 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()
    
    57. Bạn chỉ cần thực hiện một vài thay đổi đối với mã trước đó 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()
    
    1

    Lưu ý rằng mã rất giống với những gì bạn đã sử dụng trước đó. Ngoài việc làm cho mã dễ đọc hơ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()
    
    72 còn chăm sóc việc in thời gian trôi qua vào bảng điều khiển, điều này làm cho việc ghi lại thời gian dành cho sự nhất quán hơn. Khi bạn chạy mã, bạn sẽ nhận được khá nhiều đầu ra:

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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

    In thời gian trôi qua 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()
    
    72 có thể phù hợp, nhưng có vẻ như phương pháp này không linh hoạt lắm. Trong phần tiếp theo, bạn sẽ thấy cách tùy chỉnh lớp học của mình.

    Thêm sự tiện lợi và linh hoạt hơn

    Cho đến nay, bạn đã học được rằng các lớp phù hợp khi bạn muốn gói gọn trạng thái và đảm bảo hành vi nhất quán trong mã của bạn. Trong phần này, bạn sẽ thêm sự tiện lợi và linh hoạt hơn vào bộ đếm thời gian Python của bạn:

    • Sử dụng văn bản và định dạng có thể thích ứng khi báo cáo thời gian dànhadaptable text and formatting when reporting the time spent
    • Áp dụng ghi nhật ký linh hoạt, vào màn hình, vào tệp nhật ký hoặc các phần khác trong chương trình của bạnflexible logging, either to the screen, to a log file, or other parts of your program
    • Tạo bộ hẹn giờ python có thể tích lũy qua một số lời mờiaccumulate over several invocations
    • Xây dựng một đại diện thông tin của bộ đếm thời gian Pythoninformative representation of a Python timer

    Đầu tiên, xem cách bạn có thể tùy chỉnh văn bản được sử dụng để báo cáo thời gian dành. Trong mã trước, văn bả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 https://realpython.com/python-timer/ »
    
    * * *
    
    10 được mã hóa cứng thà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()
    
    83. Bạn có thể thêm tính linh hoạt cho các lớp bằng các biến thể hiện, có giá trị thường được truyền dưới dạng đối số 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()
    
    92 và được lưu trữ dưới dạng các thuộc tí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 https://realpython.com/python-timer/ »
    
    * * *
    
    13. Để thuận tiện, bạn cũng có thể cung cấp các giá trị mặc định hợp lý.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()
    
    92 and stored as
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    13 attributes. For convenience, you can also provide reasonable default values.

    Để thêm

    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    14 dưới dạng biến thể 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()
    
    72, bạn sẽ làm một cái gì đó như thế này 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()
    
    84:

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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

    Lưu ý rằng văn bản mặc đị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 https://realpython.com/python-timer/ »
    
    * * *
    
    17, được đưa ra dưới dạng chuỗi thông thường, không phải là chuỗi F. Bạn có thể sử dụng một chuỗi F ở đây vì F-Strings đánh giá ngay lập tức và khi bạn khởi tạ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()
    
    72, mã của bạn vẫn chưa tính toán thời gian trôi qua.

    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()
    
    83, 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 https://realpython.com/python-timer/ »
    
    * * *
    
    14 làm mẫu 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 https://realpython.com/python-timer/ »
    
    * * *
    
    21 để điền vào mẫ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()
    
    4

    Sau bản cập nhật này lê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()
    
    84, bạn có thể thay đổi văn bản như sau:

    >>>

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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

    So sánh điều này với ví dụ trước đó mà bạn đã 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()
    
    43. Cấu trúc của mã khá giống nhau, nhưng bây giờ mã rõ ràng hơn và đây là một trong những lợi ích của việc sử dụng các lớp. Bằng cách chọn cẩn thận lớp, phương thức và tên thuộc tính của bạn, bạn có thể làm cho mã của mình rất mô tả!

    Có lẽ bạn muốn tích hợ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()
    
    72 vào các thói quen ghi nhật ký của mình. Để hỗ trợ ghi nhật ký hoặc đầu ra khá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()
    
    72, bạn cần thay đổi cuộc gọi thà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 https://realpython.com/python-timer/ »
    
    * * *
    
    27 để người dùng có thể cung cấp chức năng ghi nhật ký của riêng họ. Điều này có thể được thực hiện tương tự như cách bạn tùy chỉnh văn bản trướ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()
    
    6

    Thay vì sử dụng trực tiế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 https://realpython.com/python-timer/ »
    
    * * *
    
    27, bạn tạo một biến thể hiện khác trong dòng 13,
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    29, sẽ đề cập đến một hàm lấy một chuỗi làm đối số. Ngoà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 https://realpython.com/python-timer/ »
    
    * * *
    
    27, bạn có thể sử dụng các chức năng 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 https://realpython.com/python-timer/ »
    
    * * *
    
    31 hoặc
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    32 trên các đối tượng tệp. Cũng lưu ý thử nghiệm
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    33 trong dòng 25, cho phép bạn tắt in hoàn toàn bằng cách vượt qua
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    34.

    Dưới đây là hai ví dụ cho thấy chức năng mới trong hành độ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

    Khi bạn chạy các ví dụ này trong một shell tương tác, Python sẽ tự động in giá trị trả về.

    Cải tiến thứ ba mà bạn sẽ thêm là khả năng tích lũy các phép đo thời gian. Bạn có thể muốn làm điều này, ví dụ, khi bạn gọi một hàm chậm trong một vòng lặp. 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ộ đếm thời gian python trong mã của bạn.time measurements. You may want to do this, for example, when you’re calling a slow function in a loop. You’ll add a bit more functionality in the form of named timers with a dictionary that keeps track of every Python timer in your code.

    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()
    
    57 sang 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 https://realpython.com/python-timer/ »
    
    * * *
    
    36 tải xuống và in mười hướng dẫn mới nhất từ ​​Real Python. Sau đây là một triển khai 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

    Mã vòng lặp qua các số từ 0 đến 9 và sử dụng các đối số bù làm đối số 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 https://realpython.com/python-timer/ »
    
    * * *
    
    37. 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 đề tinh tế với mã này là bạn đã đo lường không chỉ thời gian để tải xuống các hướng dẫn, mà cả thời gian Python dành cho việc 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 in ấn nê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 chính xác thời gian mà bạn đã làm sau trong những tình huống này.

    Có một số cách mà bạn có thể làm việc xung quanh điều này mà không thay đổi việc 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 https://realpython.com/python-timer/ »
    
    * * *
    
    38 hiện tại, 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ể làm điều đó chỉ với một vài dòng mã.

    Đầu tiên, bạn sẽ giới thiệu một từ điển gọi 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 https://realpython.com/python-timer/ »
    
    * * *
    
    39 như 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()
    
    72, điều đó có nghĩa là tất cả các trường hợp 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()
    
    72 sẽ chia sẻ nó. Bạn thực hiện nó bằng cách xác định nó bên ngoài bất kỳ phương pháp nào:class variable on
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    72, which means that all instances of
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    72 will share it. You implement it by defining it outside any methods:

    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 phiên bả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 https://realpython.com/python-timer/ »
    
    * * *
    
    0

    Khi bạn chạy các ví dụ này trong một shell tương tác, Python sẽ tự động in giá trị trả về.

    Cải tiến thứ ba mà bạn sẽ thêm là khả năng tích lũy các phép đo thời gian. Bạn có thể muốn làm điều này, ví dụ, khi bạn gọi một hàm chậm trong một vòng lặp. 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ộ đếm thời gian python trong mã của bạn.

    1. 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()
      
      57 sang 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 https://realpython.com/python-timer/ »
      
      * * *
      
      36 tải xuống và in mười hướng dẫn mới nhất từ ​​Real Python. Sau đây là một triển khai có thể:
      the elapsed time later in your code
    2. Mã vòng lặp qua các số từ 0 đến 9 và sử dụng các đối số bù làm đối số 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 https://realpython.com/python-timer/ »
      
      * * *
      
      37. 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:
      timers with the same name

    Một vấn đề tinh tế với mã này là bạn đã đo lường không chỉ thời gian để tải xuống các hướng dẫn, mà cả thời gian Python dành cho việc 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 in ấn nê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 chính xác thời gian mà bạn đã làm sau trong những tình huống 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 https://realpython.com/python-timer/ »
    
    * * *
    
    1

    Có một số cách mà bạn có thể làm việc xung quanh điều này mà không thay đổi việc 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 https://realpython.com/python-timer/ »
    
    * * *
    
    38 hiện tại, 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ể làm điều đó chỉ với một vài dòng mã.

    >>>

    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    2

    Khi bạn chạy các ví dụ này trong một shell tương tác, Python sẽ tự động in giá trị trả 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 https://realpython.com/python-timer/ »
    
    * * *
    
    3

    Cải tiến thứ ba mà bạn sẽ thêm là khả năng tích lũy các phép đo thời gian. Bạn có thể muốn làm điều này, ví dụ, khi bạn gọi một hàm chậm trong một vòng lặp. 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ộ đếm thời gian python trong mã của bạ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 https://realpython.com/python-timer/ »
    
    * * *
    
    4

    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()
    
    57 sang 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 https://realpython.com/python-timer/ »
    
    * * *
    
    36 tải xuống và in mười hướng dẫn mới nhất từ ​​Real Python. Sau đây là một triển khai có thể:

    >>>

    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    5

    Khi bạn chạy các ví dụ này trong một shell tương tác, Python sẽ tự động in giá trị trả về.

    Cải tiến thứ ba mà bạn sẽ thêm là khả năng tích lũy các phép đo thời gian. Bạn có thể muốn làm điều này, ví dụ, khi bạn gọi một hàm chậm trong một vòng lặp. 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ộ đếm thời gian 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()
    
    57 sang 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 https://realpython.com/python-timer/ »
    
    * * *
    
    36 tải xuống và in mười hướng dẫn mới nhất từ ​​Real Python. Sau đây là một triển khai có thể:

    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    6

    Mã vòng lặp qua các số từ 0 đến 9 và sử dụng các đối số bù làm đối số 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 https://realpython.com/python-timer/ »
    
    * * *
    
    37. 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:

    Bạn cần chú thích các biến của mình để sử dụng 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 bạn. Nếu bạn không muốn sử dụng các 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 https://realpython.com/python-timer/ »
    
    * * *
    
    58, 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 bạn.

    Dưới đây là một vài ghi chú 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()
    
    72:

    • Dòng 9: Bộ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      54 đị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()
      
      72 là một lớp dữ liệu.
      The
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      54 decorator defines
       1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """Download and print the latest tutorial from Real Python"""
       7    tutorial = feed.get_article(0)
       8    print(tutorial)
       9
      10if __name__ == "__main__":
      11    main()
      
      72 as a data class.

    • Dòng 11: Chú thí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 https://realpython.com/python-timer/ »
      
      * * *
      
      62 đặc biệt là cần thiết cho các lớp dữ liệu để chỉ đị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 https://realpython.com/python-timer/ »
      
      * * *
      
      39 là một biến lớp.
      The special
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      62 annotation is necessary for data classes to specify that
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      39 is a class variable.

    • Các 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 https://realpython.com/python-timer/ »
      
      * * *
      
      64,
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      14 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 https://realpython.com/python-timer/ »
      
      * * *
      
      66 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()
      
      72, có giá trị có thể được chỉ định khi tạo các trường hợ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()
      
      72. Tất cả đều có các giá trị mặc định đã 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 https://realpython.com/python-timer/ »
      
      * * *
      
      64,
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      14, and
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      66 will be defined as attributes on
       1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """Download and print the latest tutorial from Real Python"""
       7    tutorial = feed.get_article(0)
       8    print(tutorial)
       9
      10if __name__ == "__main__":
      11    main()
      
      72, whose values can be specified when creating
       1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """Download and print the latest tutorial from Real Python"""
       7    tutorial = feed.get_article(0)
       8    print(tutorial)
       9
      10if __name__ == "__main__":
      11    main()
      
      72 instances. They all have the given default values.

    • 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()
      
      81 là một thuộc tính đặc biệt mà sử dụng để theo dõi trạng thái của bộ đếm thời gian Python, nhưng nó nên đượ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 https://realpython.com/python-timer/ »
      
      * * *
      
      70, bạn nó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()
      
      81 nên được xóa 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()
      
      92 và biểu diễ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()
      
      72.
      Recall 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()
      
      81 is a special attribute that’s used to keep track of the state of the Python timer, but it should be hidden from the user. Using
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      70, you say 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()
      
      81 should be removed 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()
      
      92 and the representation 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()
      
      72.

    • Các dòng 17 đến 20: Bạn có thể sử dụng phương thức

      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      74 đặc biệt cho bất kỳ khởi tạo nào mà bạn cần thực hiện ngoài việc đặt các thuộc tính thể hiện. Ở đây, bạn sử dụng nó để thêm bộ hẹn giờ được đặ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 https://realpython.com/python-timer/ »
      
      * * *
      
      39.
      You can use the special
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      74 method for any initialization that you need to do apart from setting the instance attributes. Here, you use it to add named timers 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 https://realpython.com/python-timer/ »
      
      * * *
      
      39.

    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()
    
    72 mới của bạn hoạt động giống như lớp thông thường trước đây của bạn, ngoại trừ bây giờ nó có một đại diện tốt đẹ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 https://realpython.com/python-timer/ »
    
    * * *
    
    7

    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()
    
    72 mà nhất quán, linh hoạt, thuận tiện và nhiều thông tin! Bạn 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 các dự án của bạn.

    Trước khi kết thúc phần này, hãy xem lại mã nguồn đầy đủ 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()
    
    72 như hiện tại. Bạn sẽ nhận thấy việc bổ sung các gợi ý loại vào mã để thêm tài 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 https://realpython.com/python-timer/ »
    
    * * *
    
    8

    Sử dụng một lớp để tạo bộ hẹn giờ 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. Your code will read more naturally if you carefully choose class and method names.
    • 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. Your code will be easier to use if you encapsulate properties and behaviors into attributes and methods.
    • Tính linh hoạt: 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 với các giá trị mặc định thay vì các giá trị được mã hóa cứng. Your code will be reusable if you use attributes with default values instead of hard-coded values.

    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 thiết để chạy. Tuy nhiên, trong các phần tiếp theo, bạn sẽ tìm hiểu về việc sử dụng các trình quản lý và trang trí ngữ cảnh, sẽ thuận tiện hơn cho các khối và chức năng mã thời gian.

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

    Lớp 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()
    
    72 của bạn đã đi một chặng đường dài! So với bộ hẹn giờ Python đầu tiên bạn tạo, mã của bạn đã trở nên khá mạnh mẽ. Tuy nhiên, vẫn còn một chút mã nồi hơi cần thiết để sử dụng
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    72 của bạn:

    1. Đầu tiên, khởi tạo lớp học.
    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()
      
      82 trước khi khối mã mà bạn muốn thời gian.
    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()
      
      83 sau khối mã.

    May mắn thay, Python có một cấu trúc độc đáo để gọi các chức năng 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 những gì các nhà quản lý bối cảnh và câu lệnh Python từ ____283 là và cách bạn có thể tạo 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()
    
    72 để nó có thể hoạt động như một người 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()
    
    72 làm trình quản lý ngữ cảnh có thể đơn giản hóa mã của bạn.context manager. In this section, you’ll learn what context managers and Python’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 https://realpython.com/python-timer/ »
    
    * * *
    
    83 statement are, and how you can create your own. Then you’ll expand
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    72 so that it can work as a context manager as well. Finally, you’ll see how 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()
    
    72 as a context manager can simplify your code.

    Hiểu các nhà quản lý bối cảnh trong Python

    Các 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 giới thiệu bởi PEP 343 vào năm 2005 và lần đầu tiên được thực hiện trong Python 2.5. Bạn có thể nhận ra các 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 https://realpython.com/python-timer/ »
    
    * * *
    
    83:
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    83
    keyword:

    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    9

    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    87 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 tùy chọn 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 https://realpython.com/python-timer/ »
    
    * * *
    
    88. 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 https://realpython.com/python-timer/ »
    
    * * *
    
    89 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
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    89 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 https://realpython.com/python-timer/ »
    
    * * *
    
    89 thực thi. Cái 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 https://realpython.com/python-timer/ »
    
    * * *
    
    89 làm tăng một ngoại lệ.

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

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

    >>>

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    0

    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()
    
    72 mà nhất quán, linh hoạt, thuận tiện và nhiều thông tin! Bạn 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 các dự án của bạn.

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

    Điều đó có nghĩa 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 https://realpython.com/python-timer/ »
    
    * * *
    
    94 là người quản lý bối cảnh? Về mặt kỹ thuật, nó có nghĩa 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 https://realpython.com/python-timer/ »
    
    * * *
    
    94 thực hiện giao thức Trình quản lý bối cảnh. Có nhiều giao thức khác nhau làm cơ sở cho ngôn ngữ Python. Bạn có thể nghĩ về một giao thức như một hợp đồng nêu rõ các phương thức cụ thể của bạn phải thực hiện.context manager protocol. There are many different protocols underlying the Python language. You can think of a protocol as a contract that states what specific methods your code must implement.

    Giao thức Trình quản lý bối cảnh bao gồm hai phương pháp:

    1. Gọi
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      03 khi vào bối cảnh liên quan đến Trình quản lý ngữ cảnh.
      when entering the context related to the context manager.
    2. Gọi
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      04 Khi thoát khỏi bối cảnh liên quan đến Trình quản lý ngữ cảnh.
      when exiting the context related to the context manager.

    Nói cách khác, để tự tạo một người quản lý bối cảnh, bạn cần viết một lớp thực hiện

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 và
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04. Không nhiều không ít. Hãy thử một lời chào, thế giới! Ví dụ về Trình quản lý bối cảnh:

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    1

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    07 là người quản lý bối cảnh vì nó thực hiện giao thức Trình quản lý ngữ cảnh. Bạn có thể sử dụng nó như thế này:

    >>>

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    2

    Đầu tiên, lưu ý cách

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 được gọi trước khi bạn làm công cụ, trong khi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 được gọi sau. Trong ví dụ đơn giản hóa 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 phải đặt tên cho người quản lý bối cảnh với
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    10.

    Tiếp theo, hãy chú ý cách

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 trả 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 https://realpython.com/python-timer/ »
    
    * * *
    
    13. Giá trị trả về của
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 bị ràng buộc bởi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    10. Bạn thường muốn trả lạ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 https://realpython.com/python-timer/ »
    
    * * *
    
    13 từ
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 khi tạo người quản lý ngữ cảnh. Bạn có thể sử dụng giá trị trả về đó như sau:

    >>>

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    3

    Đầu tiên, lưu ý cách

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 được gọi trước khi bạn làm công cụ, trong khi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 được gọi sau. Trong ví dụ đơn giản hóa 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 phải đặt tên cho người quản lý bối cảnh với
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    10.

    Tiếp theo, hãy chú ý cách

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 trả 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 https://realpython.com/python-timer/ »
    
    * * *
    
    13. Giá trị trả về của
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 bị ràng buộc bởi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    10. Bạn thường muốn trả lạ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 https://realpython.com/python-timer/ »
    
    * * *
    
    13 từ
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 khi tạo người quản lý ngữ cảnh. Bạn có thể sử dụng giá trị trả về đó như sau:

    >>>

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    4

    Đầu tiên, lưu ý cách

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 được gọi trước khi bạn làm công cụ, trong khi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 được gọi sau. Trong ví dụ đơn giản hóa 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 phải đặt tên cho người quản lý bối cảnh với
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    10.

    Tiếp theo, hãy chú ý cách

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 trả 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 https://realpython.com/python-timer/ »
    
    * * *
    
    13. Giá trị trả về của
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 bị ràng buộc bởi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    10. Bạn thường muốn trả lạ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 https://realpython.com/python-timer/ »
    
    * * *
    
    13 từ
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 khi tạo người quản lý ngữ cảnh. Bạn có thể sử dụng giá trị trả về đó như sau:

    Cuối cùng, >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 04 có ba đối số: >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 18, >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 19 và >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 20. Chúng được sử dụng để xử lý lỗi trong trình quản lý ngữ cảnh và chúng phản ánh các giá trị trả về của >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 21.

    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

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 với loại ngoại lệ, một thể hiện ngoại lệ và đối tượng TraceBack. 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 đó
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 được gọi trước khi ngoại lệ được đọc lại:

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

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    24 được in, mặc dù có một lỗi trong mã.

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    5

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

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    25 trong thư viện tiêu chuẩn. Nó bao gồm các cách thuận tiện để xác định các nhà quản lý bối cảnh mới, cũng như các nhà quản lý bối cảnh làm sẵn mà bạn có thể sử dụng để đóng các đối tượng, triệt tiêu lỗi hoặc thậm chí không làm gì cả! Để biết thêm thông tin, hãy xem các nhà quản lý bối cảnh và câu lệnh Python từ ____283.

    >>>

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    6

    Đầu tiên, lưu ý cách

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 được gọi trước khi bạn làm công cụ, trong khi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 được gọi sau. Trong ví dụ đơn giản hóa 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 phải đặt tên cho người quản lý bối cảnh với
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    10.

    1. Tiếp theo, hãy chú ý cách

      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      03 trả 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 https://realpython.com/python-timer/ »
      
      * * *
      
      13. Giá trị trả về của
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      03 bị ràng buộc bởi
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      10. Bạn thường muốn trả lạ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 https://realpython.com/python-timer/ »
      
      * * *
      
      13 từ
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      03 khi tạo người quản lý ngữ cảnh. Bạn có thể sử dụng giá trị trả về đó như sau:
      returns
      $ 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 https://realpython.com/python-timer/ »
      
      * * *
      
      13, 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()
      
      72 instance, which allows the user to bind 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()
      
      72 instance to a variable using
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      10. For example,
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      43 will create the variable
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      44 pointing to 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()
      
      72 object.

    2. Cuối cùng,

      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      04 có ba đối số:
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      18,
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      19 và
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      20. Chúng được sử dụng để xử lý lỗi trong trình quản lý ngữ cảnh và chúng phản ánh các giá trị trả về của
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      21.
      expects three arguments with information about any exception that occurred during the execution of the context. In your code, these arguments are packed into a tuple called
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      47 and then ignored, which 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()
      
      72 won’t attempt any exception handling.

    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

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 với loại ngoại lệ, một thể hiện ngoại lệ và đối tượng TraceBack. 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 đó
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 được gọi trước khi ngoại lệ được đọc lại:

    >>>

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    7

    Đầu tiên, lưu ý cách

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    03 được gọi trước khi bạn làm công cụ, trong khi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 được gọi sau. Trong ví dụ đơn giản hóa 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 phải đặt tên cho người quản lý bối cảnh với
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    10.

    Tiếp theo, hãy chú ý cách >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 03 trả 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 https://realpython.com/python-timer/ » * * * 13. Giá trị trả về của >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 03 bị ràng buộc bởi >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 10. Bạn thường muốn trả lạ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 https://realpython.com/python-timer/ » * * * 13 từ >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 03 khi tạo người quản lý ngữ cảnh. Bạn có thể sử dụng giá trị trả về đó như sau:

    Cuối cùng,

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    04 có ba đối số:
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    18,
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    19 và
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    20. Chúng được sử dụng để xử lý lỗi trong trình quản lý ngữ cảnh và chúng phản ánh các giá trị trả về của
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    21.

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    8

    Bạn có thể gọi cuộc gọi đế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 https://realpython.com/python-timer/ »
    
    * * *
    
    37. Bạn có thể sử dụng Trình quản lý ngữ cảnh để làm cho mã ngắn hơn, đơn giản hơn và dễ đọc hơn:

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    9

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

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    44, giúp giữ cho 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()
    
    0

    Có một vài lợi thế để thêm các khả năng của Trình quản lý ngữ cảnh vào lớp hẹn giờ Python của bạn:

    • Nỗ lực thấp: Bạn chỉ cần thêm một dòng mã để thời gian thực hiện một khối mã. You only need one extra line of code to time the execution of a block of code.
    • Khả năng đọc: Gọi trình quản lý bối cảnh có thể đọc được và bạn có thể trực quan hóa rõ hơn khối mã mà bạn có thời gian. Invoking the context manager is readable, and you can more clearly visualize the code block that you’re timing.

    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()
    
    72 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()
    
    82 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()
    
    83, trong khi nó có mã dễ nồi hơi. Trong phần tiếp theo, bạn sẽ học cách 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()
    
    72 như một người 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.

    Một người trang trí đồng hồ Python

    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()
    
    72 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. Nói rằng bạn muốn theo dõi thời gian dành cho một chức năng nhất định trong cơ sở mã của bạn. 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()
      
      72 mỗi khi bạn gọi 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()
      
      1

      Nếu bạn gọi

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

    2. Bao 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()
      
      2

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

    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()
    
    72 làm người trang trí. Các nhà trang trí là các cấu trúc mạnh mẽ mà bạn sử dụng để sửa đổi hành vi của các chức năng và các lớp. Trong phần này, bạn sẽ tìm hiểu một chút về cách các nhà trang trí hoạt động, làm thế nào 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()
    
    72 để trở thành một người trang trí và làm thế nào điều đó sẽ đơn giản hóa các chức năng thời gian. Để biết giải thích chuyên sâu hơn về các nhà trang trí, hãy xem Primer trên các nhà trang trí Python.decorator. Decorators are powerful constructs that you use to modify the behavior of functions and classes. In this section, you’ll learn a little about how decorators work, how you can extend
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    72 to be a decorator, and how that will simplify timing functions. For a more in-depth explanation of decorators, see Primer on Python Decorators.

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

    Một người trang trí là một chức năng kết thúc một chức năng khác để sửa đổi hành vi của nó. Kỹ thuật này là có thể bởi vì các chức năng là các đối tượng hạng nhất 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.decorator is a function that wraps another function to modify its behavior. This technique is possible because functions are first-class objects in Python. In other words, functions can be assigned to variables and used as arguments to other functions, just like any other object. This gives you a lot of flexibility and is the basis for several of Python’s most powerful features.

    Ví dụ đầu tiên, bạn sẽ tạo ra một người 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()
    
    3

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

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68 chỉ là một chức năng thông thường. Điều làm cho nó trở thành một nhà trang trí là nó có một chức năng như đối số duy nhất của nó và trả về một chức năng. Bạn có thể sử dụng
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68 để 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()
    
    4

    Dòng

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    70 trang trí câu lệnh in với bộ trang trí
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68. Thực tế, nó thay thế
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    27 bằng
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    73 được trả về bởi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68. Câu lệnh Lambda đại diện cho một hàm ẩn danh không làm gì ngoại trừ return
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    95.decorates the print statement with the
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68 decorator. Effectively, it replaces
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    27 with
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    73 returned by
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68. The lambda statement represents an anonymous function that does nothing except return
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    95.

    Để xác định các nhà trang trí thú vị hơn, bạn cần biết về các chức năng bên trong. Một hàm bên trong là một hàm 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 ra các nhà máy chức năng:inner function is a function that’s defined inside another function. One common use of inner functions is to create function factories:

     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

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    76 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
    
    77. 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
    
    78 bên trong
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    76, trong khi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    76 được xác định bên ngoài
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    77:

    >>>

     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

    Dòng

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    70 trang trí câu lệnh in với bộ trang trí
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68. Thực tế, nó thay thế
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    27 bằng
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    73 được trả về bởi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68. Câu lệnh Lambda đại diện cho một hàm ẩn danh không làm gì ngoại trừ return
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    95.

    >>>

     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
    
    70 trang trí câu lệnh in với bộ trang trí
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68. Thực tế, nó thay thế
    $ 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 https://realpython.com/python-timer/ »
    
    * * *
    
    27 bằng
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    73 được trả về bởi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    68. Câu lệnh Lambda đại diện cho một hàm ẩn danh không làm gì ngoại trừ return
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    95.

     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

    Để xác định các nhà trang trí thú vị hơn, bạn cần biết về các chức năng bên trong. Một hàm bên trong là một hàm 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 ra các nhà máy chức năng:

    • >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      76 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
      
      77. 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
      
      78 bên trong
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      76, trong khi
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      76 được xác định bên ngoài
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      77:
      starts the definition of
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      83 and expects a function as an argument.
    • Thay vào đó, bạn sử dụng
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      77 để 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:
      define the inner function
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      85.
    • Tương tự, bạn có thể sử dụng các chức năng bên trong để tạo ra các nhà trang trí. Hãy nhớ rằng, một người trang trí là một hàm trả về một chức năng: returns
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      85.

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    83 là một người 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
    
    84, là đố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
    
    85. 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
    
    83:

    • 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
      
      83 và mong đợi một chức năng như một đối số.
      starts the definition of
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      85. This function will replace whichever function
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      83 decorates. The parameters are
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      92 and
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      93, which collect whichever positional and keyword arguments you pass to the function. This gives you the flexibility to use
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      83 on any function.
    • Các 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
      
      85.
      prints out the name of the decorated function and notes that
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      83 has been applied to it.
    • Dòng 4 gọi
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      84, chức năng mà
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      83 đã trang trí. Nó truyền lại tất cả các đối số được chuyển cho
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      85.
      calls
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      84, the function that
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      83 has decorated. It passes on all arguments passed to
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      85.
    • Dòng 5 gấp ba giá trị trả về của
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      84 và trả về nó.
      triples the return value of
      >>> import time
      >>> time.perf_counter()
      32311.48899951
      
      >>> time.perf_counter()  # A few seconds later
      32315.261320793
      
      84 and returns it.

    Hãy thử nó ra!

     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()
    
    00 là một hàm trả về 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()
    
    01. Xem điều gì xảy ra nếu nó tăng gấp ba lầ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()
    
    9

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

     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()
    
    01 lặp lại ba lần. Trang trí xảy ra tạ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()
    
    03.

    Nó cảm thấy hơi khó hiểu khi tiếp tục lặp lạ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()
    
    04. 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 nhà trang trí. Định nghĩa sau đây 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()
    
    00 không giống như ở trên:

    >>>

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

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

     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()
    
    01 lặp lại ba lần. Trang trí xảy ra tạ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()
    
    03.

    Nó cảm thấy hơi khó hiểu khi tiếp tục lặp lạ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()
    
    04. 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 nhà trang trí. Định nghĩa sau đây 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()
    
    00 không giống như ở trên:

    >>>

    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 đó
     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()
    
    01 lặp lại ba lần. Trang trí xảy ra tạ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()
    
    03.

    Nó cảm thấy hơi khó hiểu khi tiếp tục lặp lạ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()
    
    04. 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 nhà trang trí. Định nghĩa sau đây 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()
    
    00 không giống như ở trên:

    Biểu tượ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()
    
    06 được sử dụng để áp dụng các nhà trang trí. Trong trường hợp 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()
    
    07 có nghĩa là
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    83 được áp dụng cho hàm được xác định ngay sau nó.

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

    Một trong số ít các nhà trang trí được xác định trong thư viện tiêu chuẩ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()
    
    09. Điều này khá hữu ích khi xác định trang trí của riêng bạn. Bởi vì các nhà trang trí thay thế hiệu quả một chức năng bằng một chức năng khác, họ tạo ra một vấn đề tinh tế 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
    
    [ ... ]
    
    3

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

     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()
    
    01 lặp lại ba lần. Trang trí xảy ra tạ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()
    
    03.

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

    Nó cảm thấy hơi khó hiểu khi tiếp tục lặp lạ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()
    
    04. 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 nhà trang trí. Định nghĩa sau đây 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()
    
    00 không giống như ở trên:

    Biểu tượ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() 06 được sử dụng để áp dụng các nhà trang trí. Trong trường hợp 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() 07 có nghĩa là >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 83 được áp dụng cho hàm được xác định ngay sau nó.

    Một trong số ít các nhà trang trí được xác định trong thư viện tiêu chuẩ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()
    
    09. Điều này khá hữu ích khi xác định trang trí của riêng bạn. Bởi vì các nhà trang trí thay thế hiệu quả một chức năng bằng một chức năng khác, họ tạo ra một vấn đề tinh tế 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
    
    [ ... ]
    
    1

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    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()
    
    07 Trang trí
     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()
    
    00, 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
    
    85, như đầu ra trên xác nhận. Điều này cũng sẽ thay thế tên, DocString và các siêu dữ liệu khác. Thông thường, chiến thắng này có nhiều hiệu quả, nhưng nó có thể làm cho nội tâm khó khăn.

    >>>

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

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

     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()
    
    01 lặp lại ba lần. Trang trí xảy ra tạ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()
    
    03.

    >>>

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

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

     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()
    
    01 lặp lại ba lần. Trang trí xảy ra tạ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()
    
    03.

    >>>

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

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

     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()
    
    01 lặp lại ba lần. Trang trí xảy ra tạ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()
    
    03.

    Nó cảm thấy hơi khó hiểu khi tiếp tục lặp lạ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()
    
    04. 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 nhà trang trí. Định nghĩa sau đây 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()
    
    00 không giống như ở trên:callables. There are many callable types in Python. You can make your own objects callable by defining the special
     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()
    
    25 method in their class. The following function and class behave similarly:

    >>>

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

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

     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()
    
    01 lặp lại ba lần. Trang trí xảy ra tạ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()
    
    03.

    Nó cảm thấy hơi khó hiểu khi tiếp tục lặp lạ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()
    
    04. 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 nhà trang trí. Định nghĩa sau đây 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()
    
    00 không giống như ở trên:

    $ python -m pip install codetiming
    
    0

    Biểu tượ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()
    
    06 được sử dụng để áp dụng các nhà trang trí. Trong trường hợp 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()
    
    07 có nghĩa là
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    83 được áp dụng cho hàm được xác định ngay sau nó.

    Một trong số ít các nhà trang trí được xác định trong thư viện tiêu chuẩ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()
    
    09. Điều này khá hữu ích khi xác định trang trí của riêng bạn. Bởi vì các nhà trang trí thay thế hiệu quả một chức năng bằng một chức năng khác, họ tạo ra một vấn đề tinh tế với các chức năng của bạn:

    >>>

    $ python -m pip install codetiming
    
    1

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

     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()
    
    07 Trang trí
     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()
    
    00, 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
    
    85, như đầu ra trên xác nhận. Điều này cũng sẽ thay thế tên, DocString và các siêu dữ liệu khác. Thông thường, chiến thắng này có nhiều hiệu quả, nhưng nó có thể làm cho nội tâm khó khăn.

    $ python -m pip install codetiming
    
    2

    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()
    
    34 theo cách này, bạn không cần phải tự mình thực hiệ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()
    
    25, vì vậy bạn có thể xóa nó một cách an toà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()
    
    72.

    Sử dụng máy trang trí đồng hồ 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()
    
    57 lần cuối, sử dụng bộ hẹn giờ Python làm người trang trí:

    $ python -m pip install codetiming
    
    3

    Nếu bạn so sánh việc thực hiện này với triển khai ban đầu mà không có bất kỳ thời gian nào, thì bạn sẽ nhận thấy rằng sự khác biệt duy nhất là 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()
    
    72 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()
    
    41 trên dòng 6. Một lợi thế đáng kể của việc sử dụng các nhà trang trí là chúng Thường đơn giản để áp dụng, như bạn thấy ở đây.

    Tuy nhiên, người trang trí 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 để in hướng dẫn, ngoài thời gian cần tải xuống. Chạy tập lệnh một lần cuối cùng:

    $ python -m pip install codetiming
    
    4

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

    Khi bạn sử dụng

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

    • Nỗ lực thấp: Bạn chỉ cần thêm một dòng mã để thời gian thực hiện một hàm. You only need one extra line of code to time the execution of a function.
    • Khả năng đọc: Khi bạn thêm bộ trang trí, bạn có thể lưu ý rõ hơn rằng mã của bạn sẽ có thời gian chức năng. When you add the decorator, you can note more clearly that your code will time the function.
    • Tính nhất quán: Bạn chỉ cần thêm bộ trang trí khi hàm được xác định. Mã của bạn sẽ nhất quán thời gian nó mỗi khi nó gọi. You only need to add the decorator when the function is defined. Your code will consistently time it every time it’s called.

    Tuy nhiên, các nhà trang trí không linh hoạt như các nhà quản lý bối cảnh. Bạn chỉ có thể áp dụng chúng để hoàn thành các chức năng. Nó có thể thêm các nhà trang trí vào các chức năng đã được xác định, nhưng đây là một chút lộn xộn 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ộ đếm thời gian Python của bạn:

    $ python -m pip install codetiming
    
    5

    Mã này cũng có sẵn trong kho

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """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 trên GitHub.

    Bạn có thể tự mình sử dụng mã bằng cách lưu nó vào một 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()
    
    84 và nhập nó vào chương trình của bạn:

    >>>

    $ python -m pip install codetiming
    
    6

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    72 cũng có sẵn trên PYPI, vì vậy một tùy chọn thậm chí 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()
    
    55:

    $ 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()
    
    73. Bạn cần phải 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()
    
    72:

    >>>

    $ python -m pip install codetiming
    
    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()
    
    72 cũng có sẵn trên PYPI, vì vậy một tùy chọn thậm chí 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()
    
    55:

    1. 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()
      
      73. Bạn cần phải 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()
      
      72:class:

      $ python -m pip install codetiming
      
      9

    2. 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()
      
      49 hoạt động chính xác 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()
      
      50. Để tóm tắt, 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()
      
      72 theo ba cách khác nhau:context manager:

      >>> import time
      >>> type(time)
      
      
      >>> time.__class__
      
      
      0

    3. Như một lớp học:decorator:

      >>> import time
      >>> type(time)
      
      
      >>> time.__class__
      
      
      1

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

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

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

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

    Có nhiều tùy chọn để định thời mã của bạn với Python. Trong hướng dẫn này, bạn đã học cách tạo ra 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. Một tìm kiếm nhanh trên PYPI cho thấy rằng đã có nhiều dự án có sẵn cung cấp các 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 lý do tại sao

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    43 là thích hợp hơn. Sau đó, bạn sẽ khám phá các lựa chọn thay thế để tối ưu hóa mã của 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()
    
    72 không phù hợ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()
      
      45
    •  1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """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
    •  1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """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
    •  1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """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

    Sử dụng các chức năng hẹn giờ python thay thế

    >>>

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    2

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    72 cũng có sẵn trên PYPI, vì vậy một tùy chọn thậm chí 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()
    
    55:

    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()
    
    73. Bạn cần phải 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()
    
    72:space between the numbers that you can express. This has some consequences when you use 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()
    
    60 to represent time.

    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()
    
    49 hoạt động chính xác 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()
    
    50. Để tóm tắt, 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()
    
    72 theo ba cách khác nhau:nanosecond differences:

    >>>

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    3

    Một nanosecond là một tỷ của mộ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
    
    44 không ảnh hưởng đến kết quả.
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    43, mặt khác, sử dụng một số điểm không xác định theo thời gian làm kỷ nguyên của nó, cho phép nó hoạt động với các số nhỏ hơn và do đó có được độ phân giải tốt hơn:

    >>>

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    4

    Ở đâ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()
    
    68 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# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    45, hãy xem Hướng dẫn dành cho người mới bắt đầu về mô -đun Python Time.

    Những thách thức với thời gian đại diện cho mộ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()
    
    60 đã được 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
     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 hiện 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()
    
    47 tương ứng trả về số lượng nano giây dưới 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()
    
    38 thay vì số giây 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()
    
    60. Chẳng hạ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()
    
    45 hiện có một đối tác NanoSecond 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()
    
    76:

    >>>

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    5

    Các số nguyên không bị ràng buộc 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()
    
    76 đưa ra độ phân giải nano giây cho tất cả sự vĩnh cửu. 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()
    
    48 là một biến thể nano giây 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()
    
    43:

    >>>

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    6

    Bởi 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()
    
    43 đã 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()
    
    48.

    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")
    
    1 không đo thời gian ngủ. Đây 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()
    
    44 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()
    
    46, rất 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()
    
    72, bạn thường muốn đo toàn bộ thời gian. Hàm cuối cùng trong danh sách trên 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()
    
    42. Cái tên ám chỉ chức năng này là một bộ đếm thời gian đơn điệu, đó là một bộ đếm thời gian python không bao giờ có thể di chuyển ngược.

    Tất cả các chức năng này là đơn điệu ngoại 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()
    
    45, có thể đi ngược nếu thời gian hệ thống được điều chỉnh. Trên một số hệ thố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()
    
    42 có chức năng tương tự 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()
    
    43 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()
    
    90 để có thêm thông tin về chức năng hẹn giờ Python:

    >>>

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    7

    Kết quả có thể khác nhau 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()
      
      91: Thời gian chờ và lập lịch, không bị ảnh hưởng bởi các bản cập nhật đồng hồ hệ thố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()
      
      40: Đ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()
      
      93: Hồ sơ, thời gian CPU của quy trình (nguồn)

    Như bạn có thể nó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()
    
    43 thường là lựa chọn tốt nhất cho bộ đếm thời gian Python của bạn.

    Ướ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() 95

    Giả sử bạn đang cố gắng vắt hiệu suất cuối cùng ra khỏi mã của mình và bạn đang tự hỏi về cách hiệu quả nhất để chuyển đổi danh sách thành một bộ. 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()
    
    96 và thiết lập theo nghĩa đen,
     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()
    
    97. Bạn có thể sử dụng bộ đếm thời gian Python của mình cho việc này:

    >>>

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    8

    Thử nghiệm này dường như chỉ ra rằng chữ đã thiết lập 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ả cực kỳ khác nhau. Điều đó bởi vì bạn chỉ thử mã một lần. Ví dụ, bạn có thể không may mắn và chạy tập lệnh giống như máy tính của bạn đang trở nên bận rộn với các tác vụ khác.

    Một cách tốt hơn là sử dụng thư viện tiêu 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()
    
    95. Nó đã thiết kế chính xác để đo thời gian thực hiện 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()
    
    99 từ Python như một hàm thông thường, nhưng nó thường thuận tiện hơn khi sử dụng giao diện dòng lệnh. Bạn có thể thời gian hai biến thể như sau:

    >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    9

     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 tự động gọi mã của bạn nhiều lần để trung bình các phép đo ồn ào. Các 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()
    
    95 xác nhận rằng chữ đã thiết lập 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()
    
    96.

    Cuối cùng, Shell Interactive Ipython và Notebook Jupyter có hỗ trợ thêm cho chức năng này với lệnh

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

    >>>

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    0

    Một lần nữa, các phép đo chỉ ra rằng sử dụng một thiết lập theo nghĩa đen nhanh hơn. Trong máy tính xách tay Jupyter, bạn cũng có thể sử dụng ma thuật tế bào

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    04 để đo thời gian chạy toàn bộ ô.

    Tìm kiếm tắc nghẽn trong mã của bạn với các trình cấu hì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()
    
    95 là tuyệt vời để đánh giá một đoạn mã cụ thể. Tuy nhiên, sẽ rất cồng kềnh khi sử dụng nó để kiểm tra tất cả các phần của chương trình của bạn và định vị phần nào mất nhiều thời gian nhất. Thay vào đó, bạn có thể sử dụng một trình hồ sơ.profiler.

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    06 là một trình 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ù nó thường đơn giản nhất khi sử dụng nó như một công cụ dòng lệnh:

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    1

    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()
    
    57 khi được bật định lập. Bạn lưu đầu ra từ
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    06 trong
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    09, theo quy định của tùy chọn
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    10. 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 tiêu chuẩn! Chạy mô -đun
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    11 trên tệp
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    12 của bạn mở trình duyệt thống kê hồ sơ tương tác:

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    2

    Để sử dụng

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    11, bạn nhập các lệnh tại dấu nhắc. Ở đâ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
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    14 và
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    15. Để có được đầu ra sạch hơn,
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    16 có thể hữu ích:

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    3

    Đầ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 nơi 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 (

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    17), điều đó có nghĩa là mã của bạn tính thời gian khi hàm đã cho được gọi là một hàm khác.

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

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    18 và đặc biệt là bên trong
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    19. Mặc dù điều này có thể là xác nhận hữu ích về những gì bạn đã biết, nhưng nó thường thú vị hơn khi tìm thấy mã của bạn thực sự dành thời gian.

    Cột tổng thời gian (

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    20) cho biết mã của bạn dành bao nhiêu thời gian trong một hàm, 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 để làm điều này. Để tìm mã dành phần lớn thời gian của nó, hãy đưa ra một lệnh
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    14 khác:

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    4

    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()
    
    57 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
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    23. Cái sau là một trong những phụ thuộc của đầu đọc Python thực sự mà Lừa sử dụng để phân tích thức ăn hướng dẫn.

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

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    11 để có một số ý tưởng về nơi mã của bạn dành phần lớn thời gian và sau đó cố gắng tối ưu hóa bất kỳ nút thắt nào bạn tìm thấy. Bạn cũng có thể sử dụng công cụ để hiểu cấu trúc của mã của bạn tốt hơn. 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
    
    [ ... ]
    
    25 và
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    26 sẽ hiển thị cho bạn những chức năng nào được gọi và được gọi bởi một hàm nhất định.bottlenecks you find. You can also use the tool to understand the structure of your code better. For instance, the commands
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    25 and
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    26 will show you which functions call and are called by a given function.

    Bạn cũng có thể điều tra các chức năng nhất định. Kiểm tra số lượng chi phí

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

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    5

    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()
    
    72 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
    
    [ ... ]
    
    30 để rời trình duyệt
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    11 khi bạn điều tra xong.

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

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    06 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
    
    [ ... ]
    
    33:

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    6

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

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    09 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 mã của bạn là

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    35.
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    06 có thể cho bạn biết chức năng nào mã của bạn dành nhiều thời gian nhất, nhưng nó đã giành được cho bạn những hiểu biết sâu sắc về dòng bên trong hàm đó 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
    
    [ ... ]
    
    35 có thể giúp bạn.

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

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    06 để 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
    
    [ ... ]
    
    35 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
    
    [ ... ]
    
    35 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 các hướng dẫn cài đặt để thiết lập nó.

    Trước khi bạn chạy Profiler, bạn cần cho nó biết chức năng nào để 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
    
    [ ... ]
    
    41 bên trong mã nguồn của bạn. Ví dụ: để cấu hình
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    42, bạn thêm phần sau 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()
    
    84:

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    7

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

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    44 ở bất cứ đâu. Thay vào đó, nó tự động thêm vào không gian tên toàn cầu khi bạn chạy trình hồ sơ. Mặc dù vậy, bạn cần phải xóa dòng khi bạn thực hiện định hình. 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
    
    [ ... ]
    
    45.

    Tiếp theo, chạy trình hồ sơ bằng

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    46, 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
    
    [ ... ]
    
    35:

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    8

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

    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    48. Bạn có thể thấy 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
    
    [ ... ]
    
    35:

    >>> type(3)
    
    
    >>> type(None)
    
    
    >>> type(print)
    
    
    >>> type(type)
    
    
    9

    Đầ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
    
    [ ... ]
    
    50). Thông thường, số lượng dễ tiếp cận nhất để xem là
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    51, cho bạn biết tỷ lệ phần trăm của tổng thời gian mã của bạn dành bên trong một hàm ở 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 trên dòng 47, đó là dòng định dạng và in kết quả của bộ đếm thời gian.

    Sự 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 bạn:

    • 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 rất linh hoạt và 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()
      
      72 trực tiếp cung cấp 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.class to keep state and add a user-friendly interface. Classes are very flexible, and 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()
      
      72 directly gives you full control over how and when to invoke the timer.

    • Bạn đã sử dụng Trình quản lý ngữ 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 đó. Các nhà quản lý bối cảnh rất đơn giản để sử dụng và thêm

      $ python latest_tutorial.py
      Downloaded the tutorial in 0.6721 seconds
      # Python Timer Functions: Three Ways to Monitor Your Code
      
      [ ... ]
      
      53 có thể giúp bạn phân biệt rõ hơn mã của bạn một cách trực quan.context manager to add features to a block of code and, if necessary, to clean up afterward. Context managers are straightforward to use, and adding
      $ python latest_tutorial.py
      Downloaded the tutorial in 0.6721 seconds
      # Python Timer Functions: Three Ways to Monitor Your Code
      
      [ ... ]
      
      53 can help you more clearly distinguish your code visually.

    • Bạn đã sử dụng một người trang trí để thêm hành vi vào một chức năng. Các nhà trang trí ngắn gọn và hấp dẫn, và 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()
      
      41 là một cách nhanh chóng để theo dõi thời gian chạy mã của bạn.decorator to add behavior to a function. Decorators are concise and compelling, and using
       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 is a quick way to monitor your code’s runtime.

    Bạn cũng đã học được lý do tại sao bạn nên thí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()
    
    40 hơn
    $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    56 khi mã điểm chuẩn, cũng như những lựa chọn thay thế khác hữu ích khi bạn tối ưu hóa mã của mình.

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

    Tài nguyên

    Để đi sâu hơn vào các chức năng hẹn giờ 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()
      
      73 là bộ đếm thời gian Python có sẵn trên PYPI.
      is the Python timer available on PyPI.
    •  1# latest_tutorial.py
       2
       3from reader import feed
       4
       5def main():
       6    """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 là một bộ đếm hiệu suất cho thời gian chính xác.
      is a performance counter for precise timings.
    •  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 là một công cụ để so sánh thời gian chạy của các đoạn mã.
      is a tool for comparing the runtimes of code snippets.
    • $ python latest_tutorial.py
      Downloaded the tutorial in 0.6721 seconds
      # Python Timer Functions: Three Ways to Monitor Your Code
      
      [ ... ]
      
      06 là một trình hồ sơ để tìm kiếm tắc nghẽn trong các tập lệnh và chương trình.
      is a profiler for finding bottlenecks in scripts and programs.
    • $ python latest_tutorial.py
      Downloaded the tutorial in 0.6721 seconds
      # Python Timer Functions: Three Ways to Monitor Your Code
      
      [ ... ]
      
      11 là một công cụ dòng lệnh để xem dữ liệu hồ sơ.
      is a command-line tool for looking at profiler data.
    • Kcachegrind là GUI để xem dữ liệu hồ sơ. is a GUI for looking at profiler data.
    • $ python latest_tutorial.py
      Downloaded the tutorial in 0.6721 seconds
      # Python Timer Functions: Three Ways to Monitor Your Code
      
      [ ... ]
      
      35 là một cấu hình để đo các dòng mã riêng lẻ.
      is a profiler for measuring individual lines of code.
    • $ python latest_tutorial.py
      Downloaded the tutorial in 0.6721 seconds
      # Python Timer Functions: Three Ways to Monitor Your Code
      
      [ ... ]
      
      63 là một trình hồ sơ để theo dõi việc sử dụng bộ nhớ.
      is a profiler for monitoring memory usage.

    Làm thế nào để bạn làm cho Python đợi 5 giây?

    Nếu bạn đã có một chương trình Python và bạn muốn chờ đợi, bạn có thể sử dụng một hàm đơn giản như thế này: Time.s ngủ (x) trong đó x là số giây mà bạn muốn chương trình của bạn chờ đợi.time. sleep(x) where x is the number of seconds that you want your program to wait.