Thời gian được đo bằng Python là gì?

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

Show

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

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

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

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

Bộ hẹn giờ Python

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

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

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

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

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

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

Trăn 3. 7 đã giới thiệu một số chức năng mới, như

 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, cũng như các phiên bản nano giây của tất cả các chức năng trên, được đặt tên bằng hậu tố
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
00. Ví dụ,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
01 là phiên bản nano giây của
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
6. Bạn sẽ tìm hiểu thêm về các chức năng này sau. Hiện tại, hãy lưu ý những gì tài liệu nói về
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
6

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

Đầu tiên, bạn sẽ sử dụng

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

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ộ đếm thời gian Python vào mã của mình, bạn sẽ áp dụng các hàm bộ đếm thời gian Python khác nhau cho cùng một ví dụ mã trong suốt hướng dẫn này. Nếu bạn đã có mã mà bạn muốn đo lường, thì thay vào đó, vui lòng làm theo các ví dụ với mã đó

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()
06 để 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ề Trình đọc Python thực và cách thức hoạt động của nó, hãy xem Cách xuất bản Gói Python mã 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()
06 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()
08

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

Sau đó, bạn 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()
09

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()
10. Mã 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()
06 xử lý hầu hết các công việc khó khăn

  • Dòng 3 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()
    
    12 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()
    
    06. 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 Python thực
  • Dòng 7 tải 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()
    
    14 là 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()
    
    14 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()
    
    16 là hướng dẫn trước đó, v.v.
  • Dòng 8 in hướng dẫn ra bàn điều khiển
  • 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()
    
    17 khi bạn chạy tập lệnh

Khi bạn chạy ví dụ này, đầu ra của bạn thường trông giống như thế này

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

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

Đồng hồ bấm giờ Python đầu tiên của bạn

Bây giờ, bạn sẽ thêm một bộ đếm thời gian Python cơ bản vào ví dụ với

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
6 đo thời gian tính bằng giây từ một số thời điểm không xác định, điều đó có nghĩa là giá trị trả về của một lệnh gọi hàm không hữu ích. Tuy nhiên, khi bạn nhìn vào sự khác biệt giữa hai lần gọi đến
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
6, bạn có thể biết được có bao nhiêu giây trôi qua giữa hai lần gọi

>>>

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

Trong ví dụ này, bạn đã thực hiện hai cuộc gọi đến

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
6 cả trước và sau khi tải xuống hướng dẫn. Sau đó, bạn in thời gian cần thiết để 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

Ghi chú. Trong dòng 11,

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
23 trước chuỗi cho biết đây là chuỗi f, đây là cách thuận tiện để định dạng chuỗi văn bản.
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
24 là một công cụ xác định định dạng cho biết số,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
25, phải được in dưới dạng số thập phân có bốn số thập phân

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

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

 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

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

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

Lớp hẹn giờ Python

Nhìn lại cách bạn đã thêm bộ đếm thời gian Python vào ví dụ trên. 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()
26) để lưu trữ trạng thái của bộ đếm thời gian Python trước khi 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 tính thời gian. Bây giờ, bạn sẽ tạo một lớp thực hiện giống như các lệnh gọi thủ công của bạn tới
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
6, nhưng theo cách dễ đọc và nhất quán hơn

Xuyên 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()
28, một lớp mà bạn có thể sử dụng để định thời gian cho 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 vớ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()
29. Bạn có thể cài đặt cái này trên hệ thống của mình như vậy

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

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()
29 sau trong hướng dẫn này, trong phần có tên Mã hẹn giờ Python

Hiểu các lớp trong Python

Các lớp là khối xây dựng chính của lập trình hướng đối tượng. Về cơ bản, một lớp là một khuôn mẫu mà bạn có thể sử dụng để tạo các đối tượng. Mặc dù Python không bắt buộc bạn phải lập trình theo cách hướng đối tượng, nhưng các lớp có ở khắp mọi nơi trong ngôn ngữ này. Để chứng minh nhanh chóng, hãy đ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")
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")
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()
32 trả về loại đối tượng. Ở đây bạn có thể thấy rằng các mô-đun trên thực tế là các đối tượng được tạo từ 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()
33. Bạn có thể sử dụng thuộc tính đặ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()
34 để truy cập vào lớp định nghĩa một đối tượng. Trên thực tế, hầu hết mọi thứ trong Python đều là một lớp

>>>

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

Trong Python, các lớp rất tuyệt khi bạn cần mô hình hóa thứ gì đó cần theo dõi một trạng thái cụ thể. Nói chung, một lớp là một tập hợp các thuộc tính, được gọi là thuộc tính và hành vi, được gọi là phương thức. Để biết thêm thông tin cơ bản về các lớp và lập trình hướng đối tượng, hãy xem Lập trình hướng đối tượng (OOP) trong Python 3 hoặc tài liệu chính thức

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

Các lớp tốt cho việc theo dõi trạng thái. Trong một lớp học

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28, bạn muốn theo dõi thời điểm bắt đầu tính giờ và thời gian đã trôi qua kể từ đó. Đối với lần triển khai đầ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()
28, 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()
37, 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()
38 và
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
39. Thêm đoạn 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()
40

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

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 để xem qua mã từng bước

Ở dòng 5, bạn định nghĩa 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()
41. 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()
42 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()
41 kế thừa từ một lớp khác có tê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()
44. Python sử dụng lớp dựng sẵn 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()
41, nhưng việc có lỗi tùy chỉnh sẽ giúp bạn linh hoạt hơn trong việc xử lý sự cố 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()
28. Để biết thêm thông tin, hãy xem Ngoại lệ Python. Một lời giới thiệu

Bản thân đị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()
28 bắt đầu từ 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 sẽ 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()
48. Trong phiên bản đầu tiên 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()
28, 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()
37 mà bạn sẽ sử dụng để theo dõi trạng thái của bộ hẹn giờ 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()
51 khi bộ đếm thời gian không 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()
37 sẽ theo dõi thời điểm bộ hẹn giờ bắt đầu

Ghi chú. Tiền tố gạch dưới (

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

Khi bạn gọi

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

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

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

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

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

>>>

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

Compare this to the earlier example where you used

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
6 directly. The structure of the code is fairly similar, but now the code is clearer, and this is one of the benefits of using classes. By carefully choosing your class, method, and attribute names, you can make your code very descriptive

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

Using the Python Timer Class

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()
28 đế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()
10. You only need to make a few changes to your previous code

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

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

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

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

Printing the elapsed time from

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

Adding More Convenience and Flexibility

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

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

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

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

To add

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

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

Note that the default text,

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

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

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

One example would be

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

In

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

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

After this update to

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

>>>

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

Tiếp theo, giả sử rằng bạn không chỉ muốn in một tin nhắn ra bàn điều khiển. Có thể bạn muốn lưu số đo thời gian của mình để có thể lưu trữ chúng trong cơ sở dữ liệu. Bạn có thể làm điều này bằng cách trả về giá trị 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()
88 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()
39. Sau đó, mã gọi có thể chọn bỏ qua giá trị trả về đó hoặc lưu nó để xử lý sau

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()
28 vào thói quen ghi nhật ký của mình. Để hỗ trợ ghi nhật ký hoặc cá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()
28, bạn cần thay đổi cuộc gọi 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()
92 để 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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
92, bạn tạo một biến thể hiện khác ở dòng 13,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
94, tham chiếu đến một hàm lấy một chuỗi làm đối số. Ngoà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, bạn có thể sử dụng các hà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()
96 hoặ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()
97 trên các đối tượng tệp. Cũng lưu ý kiểm tra
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
98 ở dòng 25, cho phép bạn tắt hoàn toàn tính năng in bằng cách vượt qua
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
99

Dưới đây là hai ví dụ cho thấy chức năng mới đang hoạt động

>>>

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

Khi bạn chạy các ví dụ này trong trình bao 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 vào 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, chẳng hạn như khi bạn đang 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ộ hẹn giờ Python trong mã của bạn

Giả sử rằng bạn đang mở rộng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
10 thành tập lệnh
 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")
701 để tải xuống và in mười hướng dẫn mới nhất từ ​​Real Python. Sau đây là một thực hiện có thể

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

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

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

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

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

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
09 lưu trữ nguồn cấp dữ liệu Python thực vào lần đầu tiên
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
704 được gọi và sử dụng lại thông tin trong các lần gọi sau

Có một số cách mà bạn có thể giải quyết vấn đề này mà không thay đổi cách triển khai hiện tại của

 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")
705. Tuy nhiên, việc hỗ trợ trường hợp sử dụng này sẽ khá hữu ích và bạn có thể thực hiện chỉ với một vài dòng mã

Trước tiên, bạn sẽ giới thiệu một từ điển có tên là

 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")
706 dưới dạng một biến lớp trên
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28, có nghĩa là tất cả các phiên bản của
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 sẽ chia sẻ nó. Bạn triển khai nó bằng cách định nghĩa nó bên ngoài bất kỳ phương thức nào

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

Các biến lớp có thể được truy cập trực tiếp trên lớp hoặc thông qua một thể hiện của lớp

>>>

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

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

Tiếp theo, bạn sẽ thêm tên tùy chọn vào bộ đếm thời gian Python của mình. Bạn có thể sử dụng tên cho hai mục đích khác nhau

  1. Tra cứu thời gian đã trôi qua sau này trong mã của bạn
  2. Bộ đếm thời gian tích lũy có cùng tên

Để thêm tên vào bộ đếm thời gian Python của bạn, bạn cần thực hiện thêm hai thay đổi đố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()
40. Đầu tiên,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 nên chấp nhậ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")
711 làm tham số. Thứ hai, thời gian đã trôi qua phải được thêm và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")
706 khi đồng hồ bấm giờ dừng

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

Lưu ý rằng bạn sử dụng

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
713 khi thêm bộ đếm thời gian Python mới và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")
706. Đây là một tính năng tuyệt vời chỉ đặt giá trị nếu
 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")
711 chưa được định nghĩa trong từ điển. Nếu
 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")
711 đã được sử dụ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")
706, thì giá trị này sẽ không bị ảnh hưởng. Điều này cho phép bạn tích lũy một số bộ tính giờ

>>>

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

Giờ đây, bạn có thể truy cập lại

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
701 và đảm bảo rằng chỉ đo thời gian dành cho việc tải xuống các hướng dẫ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")
74

Chạy lại tập lệnh sẽ cho đầu ra tương tự như trước đó, mặc dù bây giờ bạn chỉ định thời gian tải xuống hướng dẫn thực tế

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

Cải tiến cuối cùng mà bạn sẽ thực hiện đối với

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 là làm cho nó có nhiều thông tin hơn khi bạn làm việc với nó một cách tương tác. Hãy thử những điều sau đây

>>>

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

Dòng cuối cùng đó là cách mặc định mà Python đại diện cho các đối tượng. Mặc dù bạn có thể thu thập một số thông tin từ nó, nhưng nó thường không hữu ích lắm. Thay vào đó, thật tuyệt khi xem thông tin như tên của

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 hoặc cách nó sẽ báo cáo về thời gian

Trong Trăn 3. 7, các lớp dữ liệu đã được thêm vào thư viện chuẩn. Chúng cung cấp một số tiện ích cho các lớp của bạn, bao gồm một chuỗi biểu diễn nhiều thông tin hơn

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

Bạn có thể cài đặt nó bằng cách sử dụng

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

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

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

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

 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")
722. Bạn sẽ tìm hiểu thêm về decorator sau trong hướng dẫn này. Hiện tại, bạn có thể coi đây là một ký hiệu cho Python biết rằng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 là một lớp dữ liệu

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

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
48 trước đó của bạn. Note how data classes use syntax that looks similar to the class variable syntax that you saw earlier for defining all variables. In fact,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """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 created automatically for data classes, based on annotated variables in the definition of the class

You need to annotate your variables to use a data class. You can use this annotation to add type hints to your code. If you don’t want to use type hints, then you can instead annotate all variables with

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
726, just like you did above. You’ll soon learn how to add actual type hints to your data class

Here are a few notes about the

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

  • Line 9. 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")
    
    722 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()
    
    28 as a data class

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

     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    730 là cần thiết cho các lớp dữ liệu để xác định rằng
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    706 là một biến lớp

  • Dòng 12 đến 14.

     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")
    
    732,
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    74 và
     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")
    
    734 sẽ được xác định là thuộc tính trên
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    28, có thể chỉ định giá trị của chúng khi tạo phiên bản
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    28. Tất cả đều có các giá trị mặc định nhất định

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

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    37 là một thuộc tính đặc biệt được sử dụng để theo dõi trạng thái của bộ đếm thời gian Python, nhưng nó phải được ẩn khỏi người dùng. Sử dụng
     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")
    
    738, bạn nói rằng nên loại bỏ
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    37 khỏi
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    48 và đại diện cho
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    28

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

     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")
    
    742 cho bất kỳ khởi tạo nào mà bạn cần thực hiện ngoài việc thiết lập các thuộc tính thể hiện. Tại đây, bạn sử dụng nó để thêm bộ hẹn giờ đã đặt tên vào
     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")
    
    706

Lớp dữ liệu

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 mới của bạn hoạt động giống như lớp thông thường trước đó của bạn, ngoại trừ việc nó hiện có một biểu diễn đẹp

>>>

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

Bây giờ bạn có một phiên bản khá gọn gàng của

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 nhất quán, linh hoạt, thuận tiện và nhiều thông tin. Bạn cũng có thể áp dụng nhiều cải tiến mà bạn đã thực hiện trong phần này cho các loại lớp khác trong dự án của mình

Trước khi kết thúc phần này, hãy xem lại mã nguồn hoàn chỉnh của

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 như hiện tại. Bạn sẽ nhận thấy việc thêm các gợi ý loại vào mã để có thêm tài liệu

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

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

  • khả năng đọc. Mã của bạn sẽ đọc tự nhiên hơn nếu bạn cẩn thận chọn tên lớp và phương thức
  • Tính nhất quán. Mã của bạn sẽ dễ sử dụng hơn nếu bạn gói gọn các thuộc tính và hành vi thành các thuộc tính và phương thức
  • Uyển chuyển. Mã của bạn sẽ có thể tái sử dụng nếu bạn sử dụng các thuộc tính có giá trị mặc định thay vì các giá trị được mã hóa cứng

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

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

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()
28 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ã soạn sẵn cần thiết để sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 của bạn

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

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

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

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

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

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
755 là một số biểu thức Python trả về trình quản lý bối cảnh. Trình quản lý ngữ cảnh được tùy chọn ràng buộc với tê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")
756. Cuối cùng,
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
757 là bất kỳ khối mã Python thông thường nào. Trình quản lý bối cảnh sẽ đảm bảo rằng chương trình của bạn gọi một số mã trước khi
 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")
757 và một số mã khác sau khi
 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")
757 thực thi. Điều sau sẽ xảy ra, ngay cả khi
 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")
757 đưa ra một ngoại lệ

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

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

>>>

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

Lưu ý rằng

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
762, con trỏ tệp, không bao giờ được đóng một cách rõ ràng vì bạn đã sử dụng
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
763 làm trình quản lý ngữ cảnh. Bạn có thể xác nhận rằng
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
762 đã tự động đóng

>>>

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

Trong ví dụ này,

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
765 là một biểu thức trả về trình quản lý ngữ cảnh. Trình quản lý bối cảnh đó bị ràng buộc với tên
 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")
762. Trình quản lý bối cảnh có hiệu lực trong quá trình thực thi
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
92. Khối mã một dòng này thực thi trong ngữ cảnh của
 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")
762

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

 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")
762 là một trình quản lý bối cảnh? . Có nhiều giao thức khác nhau nằm dưới ngôn ngữ Python. Bạn có thể nghĩ về một giao thức như một hợp đồng nêu rõ những phương pháp cụ thể mà mã của bạn phải triển khai

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

  1. Gọi
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    771 khi nhập ngữ cảnh liên quan đến trình quản lý ngữ cảnh
  2. Gọi
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    772 khi thoát khỏi bối cảnh liên quan đến trình quản lý bối cảnh

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

 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")
771 và
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
772. Không nhiều không ít. Hãy thử một Hello, World. ví dụ quản lý bối cảnh

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

 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")
775 là trình quản lý bối cảnh vì nó triển khai giao thức quản lý bối cảnh. Bạn có thể sử dụng nó như thế này

>>>

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

Trước tiên, hãy lưu ý cách

 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")
771 được gọi trước khi bạn làm công việc, trong khi
 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")
772 được gọi sau. Trong ví dụ đơn giản này, bạn không tham khảo trình quản lý ngữ cảnh. Trong những trường hợp như vậy, bạn không cần đặt tên cho trình quản lý ngữ cảnh bằng
 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")
778

Tiếp theo, chú ý cách

 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")
771 trả về
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
73. Giá trị trả về của
 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")
771 bị ràng buộc bởi
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
778. Bạn thường muốn trả về
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
73 từ
 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")
771 khi tạo trình quản lý bối cảnh. Bạn có thể sử dụng giá trị trả về đó như sau

>>>

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

Cuối cùng,

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
772 có ba đối số.
 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")
786,
 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")
787 và
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
788. Chúng được sử dụng để xử lý lỗi trong trình quản lý bối cảnh và chúng phản ánh các giá trị trả về của
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
789

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

 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")
772 với loại ngoại lệ, một thể hiện ngoại lệ và một đối tượng truy nguyên. Thông thường, bạn có thể bỏ qua những điều này trong trình quản lý ngữ cảnh của mình, trong trường hợp đó,
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
772 được gọi trước khi ngoại lệ được kích hoạt lại

>>>

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

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

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

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

 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")
793 trong thư viện tiêu chuẩn. Nó bao gồm các cách thuận tiện để xác định trình quản lý ngữ cảnh mới, cũng như các trình quản lý ngữ cảnh được tạo sẵn mà bạn có thể sử dụng để đóng đối tượng, loại bỏ lỗi hoặc thậm chí không làm gì cả. Để biết thêm thông tin, hãy xem Trình quản lý bối cảnh và Tuyên bố
 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")
751 của Python

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

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

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

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

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 hoạt động như một trình quản lý ngữ cảnh, nó cần tuân thủ giao thức của trình quản lý ngữ cảnh. Nói cách khác, nó phải triển khai
 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")
771 và
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
772 để bắt đầu và dừng bộ hẹn giờ Python. Tất cả các chức năng cần thiết đã có sẵn, vì vậy bạn không cần phải viết nhiều mã mới. Chỉ cần thêm các phương thức sau vào lớp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 của bạn

 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")
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()
28 hiện là trình quản lý ngữ cảnh. Phần quan trọng của việc triển khai là
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
771 gọi
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
38 để bắt đầu bộ đếm thời gian Python khi ngữ cảnh được nhập và
 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")
772 sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
39 để dừng bộ đếm thời gian Python khi mã rời khỏi ngữ cảnh. dùng thử

>>>

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

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

  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")
    
    771 trả về
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    73, phiên bản
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    28, cho phép người dùng liên kết phiên bản
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    28 với một biến bằng cách sử dụng
     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")
    
    778. Ví dụ,
     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")
    
    111 sẽ tạo biế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")
    
    112 trỏ đến đối tượng
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    28

  2.  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")
    
    772 mong đợi ba đối số với thông tin về bất kỳ ngoại lệ nào xảy ra trong quá trình thực thi ngữ cảnh. Trong mã của bạn, các đối số này được đóng gói thành một bộ có tên là
     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")
    
    115 và sau đó bị bỏ qua, điều đó có nghĩa là
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    28 sẽ không thử bất kỳ xử lý ngoại lệ nà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")
772 không xử lý lỗi trong trường hợp này. Tuy nhiên, một trong những tính năng tuyệt vời của trình quản lý bối cảnh là chúng được đảm bảo gọi
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
772, bất kể bối cảnh thoát ra như thế nào. Trong ví dụ sau, bạn cố tình tạo ra một lỗi bằng cách chia cho 0

>>>

 1# 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")
30

Lưu ý rằng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 in ra thời gian đã trôi qua, mặc dù mã bị lỗi. Có thể kiểm tra và loại bỏ lỗi trong
 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")
772. Xem tài liệu để cho biết thêm thông tin chi tiết

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

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

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

 1# 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")
31

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
702. Bạn có thể sử dụng trình quản lý bối cảnh để làm cho mã ngắn hơn, đơn giản hơn và dễ đọc hơn

 1# 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")
32

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

 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")
112, giúp không gian tên của bạn sạch hơn

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

 1# 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")
33

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

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

Sử dụng

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

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

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

Lớp

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

  1. Sử dụng

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

     1# 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")
    
    34

    Nếu bạn gọi

     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    131 ở nhiều nơi, thì điều này sẽ trở nên cồng kềnh và khó bảo trì

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

     1# 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")
    
    35

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    28 chỉ cần được thêm vào một chỗ, nhưng điều này thêm một mức độ thụt lề cho toàn bộ định nghĩa của
     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")
    
    131

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

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

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

Trình trang trí là một chức năng bao bọc một chức năng khác để sửa đổi hành vi của nó. Kỹ thuật này có thể thực hiện được vì hàm là đố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

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

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
136 chỉ là một hàm thông thường. Điều làm cho cái này trở thành một công cụ trang trí là nó nhận một hàm làm đối số duy nhất của nó và trả về một hàm. Bạn có thể sử dụng
 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")
136 để sửa đổi các chức năng khác, như thế này

>>>

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

Dòng

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
138 trang trí câu lệnh in bằng trình trang trí
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
136. Thực tế, nó thay thế
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
92 bằng
 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")
141 được trả về bởi
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
136. Câu lệnh lambda đại diện cho một hàm ẩn danh không làm gì ngoại trừ trả về
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
51

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

 1# 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")
38

 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")
144 là một hàm bên trong, được xác định bên 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")
145. Lưu ý rằng bạn có quyền truy cập và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")
146 bên 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")
144, trong khi
 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")
144 không được xác định bên ngoài
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
145

>>>

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

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

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

>>>

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

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

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

 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")
151 là một công cụ trang trí, bởi vì nó là một hàm mong đợi một hàm,
 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")
152, làm đối số duy nhất của nó và trả về một hàm khác,
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
153. Lưu ý cấu trúc của chính
 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")
151

  • Dòng 1 bắt đầu định nghĩa của
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    151 và mong đợi một hàm làm đối số
  • Dòng 2 đến 5 xác định hàm bên 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")
    
    153
  • Dòng 6 trả về
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    153

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

  • Dòng 2 bắt đầu định nghĩa của
     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")
    
    153. Chức năng này sẽ thay thế bất kỳ chức năng nà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")
    
    151 trang trí. Các tham số là
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    160 và
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    161, thu thập bất kỳ đối số vị trí và từ khóa nào bạn chuyển đến hàm. Điều này mang lại cho bạn sự linh hoạt để sử dụng
     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")
    
    151 trên bất kỳ chức năng nào
  • Dòng 3 in ra tên của chức năng được trang trí và lưu ý rằng
     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")
    
    151 đã được áp dụng cho nó
  • Dòng 4 gọi
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    152, chức năng mà
     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")
    
    151 đã trang trí. Nó chuyển tất cả các đối số được chuyển đế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")
    
    153
  • Dòng 5 nhân ba lần giá trị trả về của
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    152 và trả về nó

dùng thử.

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
168 là một hàm trả về từ
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
169. Xem điều gì xảy ra nếu nó tăng gấp ba lầ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")
82

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
172. Thay vào đó, PEP 318 đã giới thiệu một cú pháp thuận tiện hơn để áp dụng các trình trang trí. Định nghĩa sau đây của
 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")
168 giống như định nghĩa ở 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")
83

Biểu tượng

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
174 được sử dụng để áp dụng trang trí. Trong trường hợp này,
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
175 có nghĩa là
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
151 được áp dụng cho hàm được xác định ngay sau nó

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

 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")
177. Điều này khá hữu ích khi xác định các trang trí của riêng bạn. Vì các công cụ trang trí thay thế một chức năng này bằng một chức năng khác một cách hiệu quả nên chúng tạo ra một vấn đề tế nhị với các chức năng của bạn

>>>

 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")
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")
175 tô điểm cho
 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")
168, sau đó được thay thế bằng hàm bên 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")
153, như đầu ra ở trên xác nhận. Điều này cũng sẽ thay thế tên, chuỗi tài liệu và siêu dữ liệu khác. Thông thường, điều này sẽ không có nhiều tác dụng, nhưng nó có thể gây khó khăn cho việc xem xét nội tâm.

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

 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")
177 khắc phục chính xác vấn đề này

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

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

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

Lưu ý rằng

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
168 hiện vẫn giữ tên riêng của nó, ngay cả sau khi được trang trí. Đó là hình thức tốt để sử dụng
 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")
177 bất cứ khi nào bạn xác định một người trang trí. Một kế hoạch chi tiết mà bạn có thể sử dụng cho hầu hết các nhà trang trí của mình là như sau

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

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

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

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

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

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

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

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

Lưu ý bao nhiêu

 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")
186 giống với mẫu trước đó mà bạn đã thiết lập để định thời gian cho mã Python. Bạn có thể áp dụng
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
185 như sau

>>>

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

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

>>>

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

Bởi vì

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
174 áp dụng khi các chức năng được xác định, bạn cần sử dụng biểu mẫu cơ bản hơn trong những trường hợp này. Một lợi thế của việc sử dụng trình trang trí là bạn chỉ cần áp dụng nó một lần và nó sẽ tính thời gian cho chức năng mỗi lần

>>>

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

 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")
185 thực hiện công việc. Tuy nhiên, theo một nghĩa nào đó, bạn đang quay trở lại hình vuông, vì
 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")
185 không có bất kỳ sự linh hoạt hoặc tiện lợi nào của
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28. Bạn cũng có thể làm cho lớp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 của mình hoạt động như một người trang trí không?

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

 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")
193 trong lớp của chúng. Hàm và lớp sau hoạt động tương tự

>>>

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

Ở đây,

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
194 là một thể hiện có thể gọi được và có thể bình phương số, giống như hàm
 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")
195 trong ví dụ đầu tiên

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

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

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

 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")
193 sử dụng thực tế rằng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 đã là trình quản lý bối cảnh để tận dụng các tiện ích mà bạn đã xác định ở đó. Đảm bảo rằng bạn cũng nhập
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
199 ở đầu
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
40

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

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

>>>

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

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

Dựa trên những điểm tương đồng này, có một lớp mixin được định nghĩa trong thư viện chuẩn có tên là

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
302. Bạn có thể thêm các khả năng trang trí vào các lớp trình quản lý ngữ cảnh của mình chỉ bằng cách kế thừa
 1# 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")
302

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

Khi bạn sử dụng

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
302 theo cách này, bạn không cần phải tự triển khai
 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")
193, vì vậy bạn có thể xóa nó khỏi lớp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 một cách an toàn

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

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

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

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

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

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 trên dòng 3 và ứng dụng của
 1# 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")
309 trên dòng 6. Một lợi thế đáng kể của việc sử dụng các công cụ trang trí là chúng thường dễ áp ​​dụng, như bạn thấy ở đây

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

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

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

Khi bạn sử dụng

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

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

Tuy nhiên, trình trang trí không linh hoạt như trình quản lý ngữ cảnh. Bạn chỉ có thể áp dụng chúng để hoàn thành chức năng. Có thể thêm các bộ trang trí vào các chức năng đã được xác định, nhưng điều này hơi rắc rối và ít phổ biến hơn

Mã hẹn giờ Python

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

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

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

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

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

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

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

>>>

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

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

 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

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

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

>>>

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

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

 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")
317 hoạt động chính xác như
 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")
318. Tóm lại, bạn có thể sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 theo ba cách khác nhau

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

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

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

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

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

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

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

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

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

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

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

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

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

Bạn đã sử dụng

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

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
328. Các số dấu phẩy động không chính xác về bản chất. Bạn có thể đã thấy kết quả như thế này trước đây

>>>

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

 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")
328 của Python tuân theo Tiêu chuẩn IEEE 754 cho Số học dấu phẩy động, tiêu chuẩn này cố gắng biểu diễn tất cả các số dấu phẩy động trong 64 bit. Vì có vô số số dấu phẩy động nên bạn không thể biểu diễn tất cả chúng bằng một số bit hữu hạn

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

 1# 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")
328 để biểu thị thời gian

Xem xét

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

>>>

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

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

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

>>>

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

Ở đây, bạn nhận thấy rằng việc thêm một nano giây và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")
336 thực sự ảnh hưởng đến kết quả. Để biết thêm thông tin về cách làm việc với
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
8, hãy xem Hướng dẫn dành cho người mới bắt đầu về Mô-đun thời gian Python

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

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

>>>

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

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

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

>>>

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

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

Ghi chú.

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

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

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

Có hai chức năng trong

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
8, có thể quay ngược lại nếu thời gian hệ thống được điều chỉnh. Trên một số hệ thống,
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
5 có cùng chức năng với
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
6 và bạn có thể sử dụng chúng thay thế cho nhau. Tuy nhiên, đây không phải là luôn luôn như vậy. Bạn có thể sử dụng
 1# 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")
364 để biết thêm thông tin về chức năng hẹn giờ Python

>>>

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

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

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

  •  1# 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")
    
    365. thời gian chờ và lập lịch trình, không bị ảnh hưởng bởi cập nhật đồng hồ hệ thống
  •  1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    3. điểm chuẩn, đồng hồ chính xác nhất trong thời gian ngắn
  •  1# 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")
    
    367. hồ sơ, thời gian CPU của quá trình (Nguồn)

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

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

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

Ước tính thời gian chạy với 1# 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") 369

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

 1# 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")
370 và bộ chữ,
 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")
371. Bạn có thể sử dụng bộ đếm thời gian Python của mình cho việc này

>>>

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

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

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

 1# 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")
369. Nó được thiết kế chính xác để đo thời gian thực thi của các đoạn mã nhỏ. Mặc dù bạn có thể nhập và gọi
 1# 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")
373 từ Python như một chức năng thông thường, nhưng việc sử dụng giao diện dòng lệnh thường thuận tiện hơn. Bạn có thể tính thời gian cho hai biến thể như sau

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

 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")
369 tự động gọi mã của bạn nhiều lần để lấy trung bình các phép đo nhiễu. Kết quả từ
 1# 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")
369 xác nhận rằng bộ chữ nhanh hơn
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
370

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
369 trên mã có thể tải tệp xuống hoặc truy cập cơ sở dữ liệu. Vì
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
369 tự động gọi chương trình của bạn nhiều lần, nên bạn có thể vô tình gửi thư rác cho máy chủ bằng các yêu cầu

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

 1# 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")
379

>>>

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

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

 1# 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")
380 để đo thời gian chạy toàn bộ ô

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

 1# 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")
369 là lựa chọn tuyệt vời để đo điểm chuẩn cho một đoạn mã cụ thể. Tuy nhiên, sẽ rất cồng kềnh nếu sử dụng nó để kiểm tra tất cả các phần trong chương trình của bạn và xác định phần nào chiếm nhiều thời gian nhất. Thay vào đó, bạn có thể sử dụng một hồ sơ

 1# 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")
382 là một hồ sơ mà bạn có thể truy cập bất cứ lúc nào từ thư viện tiêu chuẩn. Bạn có thể sử dụng nó theo nhiều cách, mặc dù cách đơn giản nhất là sử dụng nó như một công cụ dòng lệnh

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

Lệnh này chạy

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
10 với cấu hình được bật. Bạn lưu đầu ra từ
 1# 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")
382 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")
385, như được chỉ định bởi tùy chọ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")
386. Dữ liệu đầu ra ở định dạng nhị phân cần một chương trình chuyên dụng để hiểu ý nghĩa của nó. Một lần nữa, Python có một tùy chọn ngay trong thư viện chuẩn. Chạy mô-đun
 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")
387 trên tệp
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
388 của bạn sẽ mở trình duyệt thống kê hồ sơ tương tác

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

Để sử dụng

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
387, bạn gõ lệnh tại dấu nhắc. Tại đây bạn có thể thấy hệ thống trợ giúp tích hợp. Thông thường, bạn sẽ sử dụng các lệnh
 1# 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")
390 và
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
391. Để có được đầu ra sạch hơn,
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
392 có thể hữu ích

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

Đầu ra này cho thấy tổng thời gian chạy là 0. 586 giây. Nó cũng liệt kê mười chức năng mà mã của bạn dành phần lớn thời gian. Ở đây bạn đã sắp xếp theo thời gian tích lũy (

 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")
393), có nghĩa là mã của bạn tính thời gian khi hàm đã cho gọi một hàm khác

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

 1# 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")
394 và đặc biệt là bên 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")
395. Mặc dù đây có thể là xác nhận hữu ích về những gì bạn đã biết, nhưng sẽ thú vị hơn khi tìm thấy nơi mã của bạn thực sự dành thời gian

Cột tổng thời gian (

 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")
396) cho biết lượng thời gian mã của bạn dành cho một chức năng, không bao gồm thời gian trong các chức năng phụ. Bạn có thể thấy rằng không có chức năng nào ở trên thực sự dành thời gian cho việc này. Để tìm nơi mã dành phần lớn thời gian, hãy đưa ra một lệnh
 1# 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")
390 khác

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

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
10 thực sự dành phần lớn thời gian để làm việc với socket hoặc xử lý dữ liệu bên 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")
399. Cái sau là một trong những phần phụ thuộc của Real Python Reader được sử dụng để phân tích nguồn cấp dữ liệu hướng dẫn

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

 1# 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")
387 để biết phần nào mã của bạn dành phần lớn thời gian ở đâu và sau đó cố gắng tối ưu hóa bất kỳ tắc nghẽn nào bạn tìm thấy. Bạn cũng có thể sử dụng công cụ này để hiểu rõ hơn về cấu trúc mã của mình. Chẳng hạn, các lệnh
 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")
801 và
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
802 sẽ cho bạn biết hàm nào gọi và được gọi bởi một hàm đã cho

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 gây ra bằng cách lọc kết quả bằng cụm từ
 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")
804

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

May mắn thay,

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
28 chỉ gây ra chi phí tối thiểu. Sử dụng
 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")
806 để thoát khỏi trình duyệt
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
387 khi bạn điều tra xong

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

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

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
385 và mở KCacheGrind để phân tích dữ liệu

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

 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")
811.
 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")
382 có thể cho bạn biết chức năng nào mà mã của bạn dành nhiều thời gian nhất, nhưng nó sẽ không cung cấp cho bạn thông tin chi tiết về dòng nào bên trong chức năng đó là chậm nhất. Đó là nơi mà
 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")
811 có thể giúp bạn

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

 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")
814 nếu bạn cần theo dõi mức tiêu thụ bộ nhớ của các chương trình của mình

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

 1# 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")
382 để xác định chức năng nào cần điều tra, sau đó chạy
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
811 trên các chức năng đó.
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
811 không phải là một phần của thư viện tiêu chuẩn, vì vậy trước tiên bạn nên làm theo hướng dẫn cài đặt để thiết lập

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

 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")
818 bên trong mã nguồn của bạn. Ví dụ: với hồ sơ
 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")
819, bạn thêm phần sau vào bên trong
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
40

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

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

 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")
821 ở bất cứ đâu. Thay vào đó, nó sẽ tự động được thêm vào không gian tên chung khi bạn chạy trình lược tả. Tuy nhiên, bạn cần xóa dòng này khi hoàn tất hồ sơ. Nếu không, bạn sẽ nhận được một
 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")
822

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
823, đây là một phần của gói
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
811

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
825. Bạn có thể xem những kết quả đó bằng cách sử dụng
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
811

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

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

 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")
827). Thông thường, số dễ truy cập nhất để xem là
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
828, cho bạn biết tỷ lệ phần trăm tổng thời gian mã của bạn sử dụng bên trong một hàm tại mỗi dòng. Trong ví dụ này, bạn có thể thấy rằng mã của bạn dành gần 70 phần trăm thời gian cho dòng 47, đây là dòng định dạng và in kết quả của bộ đếm thời gian

Phần kết luận

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

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

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

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

     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")
    
    830 có thể giúp bạn phân biệt rõ ràng hơn về mã của mình một cách trực quan

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

     1# 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")
    
    309 là một cách nhanh chóng để theo dõi thời gian chạy mã của bạn

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
3 hơn là dùng
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
833 khi đo điểm chuẩn cho mã, cũng như các giải pháp thay thế khác hữu ích khi bạn tối ưu hóa mã của mình

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

Tài nguyên

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

  •  1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    29 là bộ đếm thời gian Python có sẵn trên PyPI
  •  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 là một bộ đếm hiệu suất cho thời gian chính xác
  •  1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    369 là một công cụ để so sánh thời gian chạy của các đoạn mã
  •  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")
    
    382 là một công cụ hồ sơ để tìm ra các nút cổ chai trong các tập lệnh và chương trình
  •  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")
    
    387 là một công cụ dòng lệnh để xem dữ liệu hồ sơ
  • KCachegrind là một GUI để xem dữ liệu hồ sơ
  •  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")
    
    811 là một hồ sơ để đo các dòng mã riêng lẻ
  •  1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    814 là một hồ sơ để theo dõi việc sử dụng bộ nhớ

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

🐍 Thủ thuật Python 💌

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

Thời gian được đo bằng Python là gì?

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

Giới thiệu về Geir Arne Hjelle

Thời gian được đo bằng Python là gì?
Thời gian được đo bằng Python là gì?

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

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


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

Thời gian được đo bằng Python là gì?

Aldren

Thời gian được đo bằng Python là gì?

Đan

Thời gian được đo bằng Python là gì?

Jaya

Thời gian được đo bằng Python là gì?

Joanna

Thời gian được đo bằng Python là gì?

kate

Thời gian được đo bằng Python là gì?

Mike

Thời gian được đo bằng Python là gì?

Philipp

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

Thời gian được đo bằng Python là gì?

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

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

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

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

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

Bạn nghĩ sao?

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

Tweet Chia sẻ Chia sẻ Email

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

Mẹo bình luận. Những nhận xét hữu ích nhất là những nhận xét được viết với mục đích học hỏi hoặc giúp đỡ các sinh viên khác. Nhận các mẹo để đặt câu hỏi hay và nhận câu trả lời cho các câu hỏi phổ biến trong cổng thông tin hỗ trợ của chúng tôi

Thời gian được tính bằng Python như thế nào?

Để tính thời gian thực thi mã, mô-đun thời gian có thể được sử dụng. .
Lưu dấu thời gian ở đầu mã bắt đầu sử dụng time()
Lưu dấu thời gian ở cuối mã
Tìm sự khác biệt giữa kết thúc và bắt đầu, cho biết thời gian thực hiện

%% thời gian có nghĩa là gì trong Python?

%%time là một lệnh kỳ diệu. Nó là một phần của IPython. %%time in thời gian treo tường cho toàn bộ ô trong khi %time chỉ cho bạn thời gian cho dòng đầu tiên. Sử dụng %%time hoặc %time in 2 giá trị. Thời gian CPU.