Hướng dẫn is there a timer library in python? - có thư viện hẹn giờ trong python không?

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

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

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

Đồng hồ hẹn giờ

Đầu tiên, bạn sẽ xem xét một số mã ví dụ mà bạn sẽ sử dụng trong suốt hướng dẫn. Sau đó, bạn sẽ thêm một bộ đếm thời gian python vào mã này để theo dõi hiệu suất của nó. Bạn cũng sẽ học một số cách đơn giản nhất để đo thời gian chạy của ví dụ này.Python timer to this code to monitor its performance. You’ll also learn some of the simplest ways to measure the running time of this example.

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

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

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

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

Python 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")
6, cũng như các phiên bản nano giây của tất cả các chức năng ở trên, được đặt tên với hậu tố
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
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í 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")
8 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")
3. Bạn sẽ tìm hiểu thêm về các chức năng này sau này. Hiện tại, lưu ý những gì tài liệu phải nói về
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
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:nanosecond versions of all the functions above, named with an
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
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 suffix. For example,
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
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 is the nanosecond version of
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
3. You’ll learn more about these functions later. For now, note what the documentation has to say about
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
3:

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

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

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

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

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

Ví dụ mà bạn sẽ sử dụng trong hướng dẫn này là một chức năng 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()
03 để tải xuống các hướng dẫn mới nhất có sẵn tại đây trên Real Python. Để tìm hiểu thêm về đầu đọc Python thực sự và cách thức hoạt động, hãy xem cách xuất bản gói Python nguồn mở lên PYPI. Bạn có thể cài đặt
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
03 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()
05:

$ python -m pip install realpython-reader

Sau đó, bạn có thể nhập gói dưới dạng

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

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()
07. Mã này bao gồm một chức năng tải xuống và in hướng dẫn mới nhất từ ​​Real Python:

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
03 xử lý hầu hết các công việc khó khăn:

  • Dòng 3 nhập khẩu
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    09 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()
    
    03. Mô -đun này chứa chức năng để tải xuống các hướng dẫn từ nguồn cấp dữ liệu Python thực sự.
    imports
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    09 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()
    
    03. This module contains functionality for downloading tutorials from the Real Python feed.
  • Dòng 7 Tải xuống hướng dẫn mới nhất từ ​​Real Python. Số
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    11 là một phần bù, trong đó
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    11 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()
    
    13 là hướng dẫn trước đây, v.v.
    downloads the latest tutorial from Real Python. The number
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    11 is an offset, where
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    11 means the most recent tutorial,
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    13 is the previous tutorial, and so on.
  • Dòng 8 in hướng dẫn cho bảng điều khiển. prints the tutorial to the console.
  • Dòng 11 gọi
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    14 Khi bạn chạy tập lệnh.
    calls
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    14 when you run the script.

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

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

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

[ ... ]

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

* * *

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

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

Bây giờ, bạn sẽ thêm một bộ đếm thời gian trăn trần vào ví dụ với

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
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. Một lần nữa, đây là một bộ đếm hiệu suất phù hợp với các phần thời gian của mã của bạn.performance counter that’s well-suited for timing parts of your code.

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

>>>

>>> import time
>>> time.perf_counter()
32311.48899951

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
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 cách nhau gần 4 giây. Bạn có thể xác nhận điều này bằng cách tính toán chênh lệch giữa hai đầu ra: 32315.26 - 32311,49 = 3,77.

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

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
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 cả trước và sau khi tải xuống hướng dẫn. Sau đó, bạn in thời gian để tải xuống hướng dẫn bằng cách tính toán sự khác biệt giữa hai cuộc gọi.

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

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

[ ... ]

Đó là nó! Bạn đã đề cập đến những điều cơ bản về thời gian của mã Python của riêng bạn. Trong phần còn lại của hướng dẫn, bạn sẽ tìm hiểu làm thế nào bạn có thể bọc một bộ đếm thời gian python vào một lớp học, một người quản lý bối cảnh và một người trang trí để làm cho nó phù hợp và thuận tiện hơn để sử dụng.

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

Nhìn lại cách bạn đã thêm bộ hẹn giờ python vào ví dụ trên. Lưu ý rằng bạn cần ít nhất một biến (

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
20) để lưu trữ trạng thái của bộ hẹn giờ Python trước khi bạn tải xuống hướng dẫn. Sau khi nghiên cứu mã một chút, bạn cũng có thể lưu ý rằng ba dòng được tô sáng chỉ được thêm vào cho mục đích thời gian! Bây giờ, bạn sẽ tạo ra một lớp giống như các cuộc gọi thủ công của bạ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")
3, nhưng theo cách dễ hiểu và nhất quán hơn.

Trong suốt hướng dẫn này, bạn sẽ tạo và cập nhật

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, một lớp mà bạn có thể sử dụng để thời gian mã của mình theo nhiều cách khác nhau. Mã cuối cùng với một số tính năng bổ sung cũng có sẵn trên PYPI dưới tên
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
23. Bạn có thể cài đặt nó trên hệ thống của mình như vậy:

$ python -m pip install codetiming

Bạn có thể tìm thêm thông tin về

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
23 sau này trong hướng dẫn này, trong phần có tên là mã hẹn giờ Python.

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

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

 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
1: are the main building blocks of object-oriented programming. A class is essentially a template that you can use to create objects. While Python doesn’t force you to program in an object-oriented manner, classes are everywhere in the language. For quick proof, investigate the
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
24        elapsed_time = time.perf_counter() - self._start_time
25        self._start_time = None
26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
1 module:

>>>

>>> import time
>>> type(time)


>>> time.__class__

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """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 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ế, 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()
27. 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()
28 để có quyền truy cập vào lớp xác định 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 học:

>>>

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """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 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ế, 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()
27. 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()
28 để có quyền truy cập vào lớp xác định 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 học:attributes, and behaviors, called methods. For more background on classes and object-oriented programming, check out Object-Oriented Programming (OOP) in Python 3 or the official docs.

Trong Python, các lớp học là tuyệt vời khi bạn cần mô hình hóa một cái 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 nền tảng về các lớp và lập trình hướng đối tượng, hãy xem chương trình hướng đối tượng (OOP) trong Python 3 hoặc các tài liệu chính thức.

Tạo lớp hẹn giờ Pythonstate. In a

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 class, you want to keep track of when a timer starts and how much time has passed since then. For the first implementation of
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, you’ll add a
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
31 attribute, as well as
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
32 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()
33 methods. Add the following code to a file named
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
34:

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

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, bạn muốn theo dõi thời điểm hẹn giờ bắt đầu và thời gian trôi qua kể từ đó. Đối với lần thực hiện đầu tiên của
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, 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()
31, 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()
32 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()
33. Thêm mã sau vào tệp có tên
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
34:

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

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

Trong dòng 5, bạn xác định một lớp

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
35. 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()
36 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()
35 kế thừa từ một lớp khác được gọi là
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
38. Python sử dụng lớp tích hợp này để xử lý lỗi. Bạn không cần thêm bất kỳ thuộc tính hoặc phương thức nào vào
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
35, nhưng có lỗi tùy chỉnh sẽ cho bạn linh hoạt hơn để xử lý các vấn đề bên trong
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22. Để biết thêm thông tin, hãy xem các ngoại lệ Python: Giới thiệu.instantiate an object from a class, your code calls the special method
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
42. In this first version of
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, you only initialize the
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
31 attribute, which you’ll use to track the state of your Python timer. It has the value
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
45 when the timer isn’t running. Once the timer is running,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
31 keeps track of when the timer started.

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

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()
32 để bắt đầu bộ đếm thời gian Python mới, trước tiên bạn sẽ kiểm tra xem bộ đếm thời gian có đang chạy không. Sau đó, bạn lưu trữ giá trị hiện tại 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")
3 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()
31.

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()
33, trước tiên bạn kiểm tra xem bộ đếm thời gian Python có đang chạy không. Nếu có, thì bạn tính thời gian trôi qua là chênh lệch giữa giá trị hiện tại của
 1# timer.py
 2
 3import time
 4
 5class TimerError(Exception):
 6    """A custom exception used to report errors in use of Timer class"""
 7
 8class Timer:
 9    def __init__(self):
10        self._start_time = None
11
12    def start(self):
13        """Start a new timer"""
14        if self._start_time is not None:
15            raise TimerError(f"Timer is running. Use .stop() to stop it")
16
17        self._start_time = time.perf_counter()
18
19    def stop(self):
20        """Stop the timer, and report the elapsed time"""
21        if self._start_time is None:
22            raise TimerError(f"Timer is not running. Use .start() to start it")
23
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 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()
31. 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()
31 để bộ hẹn giờ có thể được khởi động lại và in thời gian trôi 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()
0

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """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 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ế, 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()
27. 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()
28 để có quyền truy cập vào lớp xác định 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 học:

Trong Python, các lớp học là tuyệt vời khi bạn cần mô hình hóa một cái 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 nền tảng về các lớp và lập trình hướng đối tượng, hãy xem chương trình hướng đối tượng (OOP) trong Python 3 hoặc các tài liệu chính thức.

Tạo lớp hẹn giờ 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

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, bạn muốn theo dõi thời điểm hẹn giờ bắt đầu và thời gian trôi qua kể từ đó. Đối với lần thực hiện đầu tiên của
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, 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()
31, 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()
32 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()
33. Thêm mã sau vào tệp có tên
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
34:

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

In thời gian trôi qua từ

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 có thể phù hợp, nhưng có vẻ như phương pháp này không linh hoạt lắm. Trong phần tiếp theo, bạn sẽ thấy cách tùy chỉnh lớp học của mình.

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

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

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

Đầu tiên, xem cách bạn có thể tùy chỉnh văn bản được sử dụng để báo cáo thời gian dành. Trong mã trước, văn bản

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
60 được mã hóa cứng thành
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
33. Bạn có thể thêm tính linh hoạt cho các lớp bằng các biến thể hiện, có giá trị thường được truyền dưới dạng đối số cho
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
42 và được lưu trữ dưới dạng các 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()
63. Để thuận tiện, bạn cũng có thể cung cấp các giá trị mặc định hợp lý.instance variables, whose values are normally passed as arguments to
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
42 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()
63 attributes. For convenience, you can also provide reasonable default values.

Để thê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()
64 dưới dạng biến thể hiện
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, bạn sẽ làm một cái gì đó như thế này trong
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
34:

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

Lưu ý rằng văn bản mặc định,

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
67, được đưa ra dưới dạng chuỗi thông thường, không phải là chuỗi F. Bạn có thể sử dụng một chuỗi F ở đây vì F-Strings đánh giá ngay lập tức và khi bạn khởi tạo
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, mã của bạn vẫn chưa tính thời gian trôi qua.

Trong

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
33, 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()
64 làm mẫu 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()
71 để điền vào mẫu:

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

Sau bản cập nhật này lên

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
34, bạn có thể thay đổi văn bản như sau:

>>>

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

Tiếp theo, giả sử rằng bạn không chỉ muốn in một tin nhắn vào bảng điều khiển. Có thể bạn muốn lưu các phép đo thời gian của mình để bạn 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()
73 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()
33. 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()
22 vào các thói quen ghi nhật ký của mình. Để hỗ trợ ghi nhật ký hoặc đầu ra khác từ
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, 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()
77 để 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()
77, bạn tạo một biến thể hiện khác trong 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()
79, sẽ đề cập đế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()
77, bạn có thể sử dụng các chức năng như
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
81 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()
82 trên các đối tượng tệp. Cũng lưu ý bài 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()
83 trong dòng 25, cho phép bạn tắt in hoàn toàn 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()
84.

Dưới đây là hai ví dụ cho thấy chức năng mới trong hành động:

>>>

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

Tiếp theo, giả sử rằng bạn không chỉ muốn in một tin nhắn vào bảng điều khiển. Có thể bạn muốn lưu các phép đo thời gian của mình để bạn 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()
73 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()
33. 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()
22 vào các thói quen ghi nhật ký của mình. Để hỗ trợ ghi nhật ký hoặc đầu ra khác từ
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, 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()
77 để 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 đó:time measurements. You may want to do this, for example, when you’re calling a slow function in a loop. You’ll add a bit more functionality in the form of named timers with a dictionary that keeps track of every Python timer in your code.

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()
77, bạn tạo một biến thể hiện khác trong 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()
79, sẽ đề cập đế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()
77, bạn có thể sử dụng các chức năng như
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
81 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()
82 trên các đối tượng tệp. Cũng lưu ý bài 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()
83 trong dòng 25, cho phép bạn tắt in hoàn toàn 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()
84.

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

Dưới đây là hai ví dụ cho thấy chức năng mới trong hành động:

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

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

Cải tiến thứ ba mà bạn sẽ thêm là khả năng tích lũy các phép đo thời gian. Bạn có thể muốn làm điều này, ví dụ, khi bạn gọi một hàm chậm trong một vòng lặp. Bạn sẽ thêm một chút chức năng dưới dạng bộ hẹn giờ được đặt tên với một từ điển theo dõi mọi bộ đếm thời gian python trong mã của bạn.

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

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
07 sang tập lệ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()
86 tải xuống và in mười hướng dẫn mới nhất từ ​​Real Python. Sau đây là một triển khai có thể:class variable on
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, which means that all instances of
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 will share it. You implement it by defining it outside any methods:

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

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

>>>

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

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

[ ... ]

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

* * *
0

Tiếp theo, giả sử rằng bạn không chỉ muốn in một tin nhắn vào bảng điều khiển. Có thể bạn muốn lưu các phép đo thời gian của mình để bạn 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()
73 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()
33. 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()
22 vào các thói quen ghi nhật ký của mình. Để hỗ trợ ghi nhật ký hoặc đầu ra khác từ
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22, 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()
77 để 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. Nhìn lên thời gian trôi qua sau này trong mã của bạn the elapsed time later in your code
  2. Tích lũy bộ hẹn giờ có cùng tên timers with the same name

Để thêm tên vào bộ hẹn giờ Python của bạn, bạn cần thực hiện thêm hai thay đổ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()
34. Đầ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()
22 nên chấp nhậ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()
94 dưới dạng tham số. Thứ hai, thời gian trôi qua nên được thêm 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()
89 khi bộ đếm thời gian dừng lại:

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

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

[ ... ]

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

* * *
1

Lưu ý rằng 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()
96 khi thêm bộ hẹn giờ Python mới 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()
89. Đây là một tính năng tuyệt vời chỉ đặt giá trị nế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()
94 đã được xác định trong từ điển. Nế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()
94 đã được sử dụng 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()
89, thì giá trị không bị ảnh hưởng. Điều này cho phép bạn tích lũy một số bộ đếm thời gian:

>>>

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

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

[ ... ]

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

* * *
2

Bây giờ bạn có thể xem 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()
86 và đảm bảo chỉ có thời gian tải xuống các hướng dẫn được đo lường:

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

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

[ ... ]

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

* * *
3

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

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

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

[ ... ]

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

* * *
4

Sự cải thiện cuối cùng mà bạn sẽ thực hiệ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()
22 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:

>>>

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

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

[ ... ]

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

* * *
5

Bây giờ bạn có thể xem 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()
86 và đảm bảo chỉ có thời gian tải xuống các hướng dẫn được đo lường:

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

Sự cải thiện cuối cùng mà bạn sẽ thực hiệ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()
22 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:

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

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

[ ... ]

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

* * *
6

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ể lượm lặt được 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 thấy 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()
22 hoặc cách nó báo cáo về thời gian.

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

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

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

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

[ ... ]

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

* * *
04. Bạn sẽ tìm hiểu thêm về các nhà trang trí sau này trong hướng dẫn này. Hiện tại, bạn có thể nghĩ về điều này như một ký hiệu cho Python nói rằng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 là một lớp dữ liệu:

  • Mã này thay thế 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()
    
    42 trước đó của bạn. Lưu ý cách các lớp dữ liệu sử dụng cú pháp trông giống với cú pháp biến lớp mà bạn đã thấy trước đó để xác định tất cả các biến. Trên thực tế,
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    42 được tạo tự động cho các lớp dữ liệu, dựa trên các biến được chú thích trong định nghĩa của lớp.
    The
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    04 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()
    
    22 as a data class.

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

    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    08, giống như bạn đã làm ở trên. Bạn sẽ sớm học cách thêm gợi ý loại thực tế vào lớp dữ liệu của bạn. The special
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    12 annotation is necessary for data classes to specify that
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    89 is a class variable.

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

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22:
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    14,
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    64, and
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    16 will be defined as attributes on
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22, whose values can be specified when creating
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 instances. They all have the given default values.

  • Dòng 9: Bộ trang trí

    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    04 định nghĩa
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 là lớp dữ liệu.
    Recall that
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    31 is a special attribute that’s used to keep track of the state of the Python timer, but it should be hidden from the user. Using
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    20, you say that
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    31 should be removed from
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    42 and the representation of
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22.

  • Dòng 11: Chú thích

    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    12 đặc biệt là cần thiết cho các lớp dữ liệu để chỉ định 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()
    
    89 là một biến lớp.
    You can use the special
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    24 method for any initialization that you need to do apart from setting the instance attributes. Here, you use it to add named timers 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()
    
    89.

Các dòng 12 đến 14:

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
16 sẽ được định nghĩa là các 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()
22, có giá trị có thể được chỉ định khi tạo các trường hợp
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22. Tất cả đều có các giá trị mặc định đã cho.

>>>

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

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

[ ... ]

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

* * *
7

Bây giờ bạn có thể xem 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()
86 và đảm bảo chỉ có thời gian tải xuống các hướng dẫn được đo lường:

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

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

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

[ ... ]

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

* * *
8

Sự cải thiện cuối cùng mà bạn sẽ thực hiệ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()
22 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:

  • 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ể lượm lặt được 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 thấy 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()
    
    22 hoặc cách nó báo cáo về thời gian.
    Your code will read more naturally if you carefully choose class and method names.
  • Trong Python 3.7, các lớp dữ liệu đã được thêm vào thư viện tiêu chuẩn. Chúng cung cấp một số tiện ích cho các lớp học của bạn, bao gồm một chuỗi đại diện nhiều thông tin hơn. Your code will be easier to use if you encapsulate properties and behaviors into attributes and methods.
  • Bạn chuyển đổi bộ đếm thời gian Python của mình thành một lớp dữ liệu bằng cách sử dụng trình trang trí
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    04. Bạn sẽ tìm hiểu thêm về các nhà trang trí sau này trong hướng dẫn này. Hiện tại, bạn có thể nghĩ về điều này như một ký hiệu cho Python nói rằng
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 là một lớp dữ liệu:
    Your code will be reusable if you use attributes with default values instead of hard-coded values.

Mã này thay thế 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()
42 trước đó của bạn. Lưu ý cách các lớp dữ liệu sử dụng cú pháp trông giống với cú pháp biến lớp mà bạn đã thấy trước đó để xác định tất cả các biến. Trên thực tế,
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
42 được tạo tự động cho các lớp dữ liệu, dựa trên các biến được chú thích trong định nghĩa của lớp.

Bạn cần chú thích các biến của mình để sử dụng lớp dữ liệu. Bạn có thể sử dụng chú thích này để thêm gợi ý loại vào mã của bạn. Nếu bạn không muốn sử dụng gợi ý loại, thì thay vào đó bạn có thể chú thích tất cả các biến bằng $ python latest_tutorial.py # Python Timer Functions: Three Ways to Monitor Your Code While many developers recognize Python as an effective programming language, pure Python programs may run more slowly than their counterparts in compiled languages like C, Rust, and Java. In this tutorial, you'll learn how to use a Python timer to monitor how quickly your programs are running. [ ... ] ## Read the full article at https://realpython.com/python-timer/ » * * * 08, giống như bạn đã làm ở trên. Bạn sẽ sớm học cách thêm gợi ý loại thực tế vào lớp dữ liệu của bạn.

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

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

May mắn thay, Python có một cấu trúc độc đáo để gọi các chức năng trước và sau một khối mã: Trình quản lý bối cảnh. Trong phần này, bạn sẽ tìm hiểu những gì các nhà quản lý bối cảnh và câu lệnh Python từ ____233 là và cách bạn có thể tạo của riêng mình. Sau đó, bạn sẽ mở rộng

 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 để nó có thể hoạt động như một người quản lý bối cảnh. Cuối cùng, bạn sẽ thấy cách sử dụng
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 làm trình quản lý ngữ cảnh có thể đơn giản hóa mã của bạn.context manager. In this section, you’ll learn what context managers and Python’s
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

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

[ ... ]

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

* * *
33 statement are, and how you can create your own. Then you’ll expand
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 so that it can work as a context manager as well. Finally, you’ll see how using
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 as a context manager can simplify your code.

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

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
33
keyword:

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

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

[ ... ]

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

* * *
9

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
39 làm tăng một ngoại lệ.

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

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

>>>

>>> import time
>>> time.perf_counter()
32311.48899951

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

Lưu ý rằng

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
44 đã đóng tự động:

Trong ví dụ này,

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
44.

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

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

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

[ ... ]

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

* * *
44 là người quản lý bối cảnh? Về mặt kỹ thuật, nó có nghĩa là
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

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

[ ... ]

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

* * *
44 thực hiện giao thức Trình quản lý bối cảnh. Có nhiều giao thức khác nhau làm cơ sở cho ngôn ngữ Python. Bạn có thể nghĩ về một giao thức như một hợp đồng nêu rõ các phương thức cụ thể của bạn phải thực hiện.context manager protocol. There are many different protocols underlying the Python language. You can think of a protocol as a contract that states what specific methods your code must implement.

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

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

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
54. Không nhiều không ít. Hãy thử một lời chào, thế giới! Ví dụ về Trình quản lý bối cảnh:

>>> import time
>>> time.perf_counter()
32311.48899951

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

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

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

[ ... ]

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

* * *
57 là người quản lý bối cảnh vì nó thực hiện giao thức Trình quản lý ngữ cảnh. Bạn có thể sử dụng nó như thế này:

>>>

>>> import time
>>> time.perf_counter()
32311.48899951

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

Lưu ý rằng

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
44 đã đóng tự động:

Trong ví dụ này,

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
44.

>>>

>>> import time
>>> time.perf_counter()
32311.48899951

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

Lưu ý rằng

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
44 đã đóng tự động:

Trong ví dụ này,

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
44.

>>>

>>> import time
>>> time.perf_counter()
32311.48899951

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

Lưu ý rằng

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
44 đã đóng tự động:

Trong ví dụ này,

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

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

[ ... ]

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

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

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

[ ... ]

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

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

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

[ ... ]

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

* * *
44.

Tạo Trình quản lý bối cảnh Python Timer

Bạn đã thấy cách các nhà quản lý ngữ cảnh làm việc nói chung, nhưng làm thế nào họ có thể giúp với mã thời gian? Nếu bạn có thể chạy một số chức năng nhất định trước và sau một khối mã, thì bạn có thể đơn giản hóa cách thức hoạt động của bộ hẹn giờ Python của bạn. Cho đến nay, bạn cần phải 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()
32 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()
33 rõ ràng khi định thời gian mã của bạn, nhưng người quản lý bối 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()
22 hoạt động như một người quản lý bối cảnh, nó cần phải tuân thủ giao thức Trình quản lý ngữ cảnh. Nói cách khác, nó phải thực hiện
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

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

[ ... ]

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

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

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

[ ... ]

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

* * *
54 để bắt đầu và dừng bộ đếm thời gian python. Tất cả các chức năng cần thiết đã có sẵn, vì vậy, không có nhiều mã mới bạn cần viết. 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()
22 của bạn:

>>> import time
>>> time.perf_counter()
32311.48899951

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

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

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

[ ... ]

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

* * *
53 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()
32 để bắt đầu bộ hẹn giờ python khi bối cảnh được nhập và
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

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

[ ... ]

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

* * *
54 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()
33 để dừng bộ đếm thời gian python khi mã rời khỏi bối cảnh. Hãy thử nó:

>>>

>>> import time
>>> time.perf_counter()
32311.48899951

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

Bạn cũng nên lưu ý hai chi tiết tinh tế hơn:

  1. $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    53 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()
    
    63, 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()
    
    22, cho phép người dùng liên kết thể hiện
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 với một biến bằng cách sử dụng
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    60. Ví dụ:
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    93 sẽ tạo biến
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    94 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()
    
    22.
    returns
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    63, 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()
    
    22 instance, which allows the user to bind the
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 instance to a variable using
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    60. For example,
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    93 will create the variable
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    94 pointing to the
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 object.

  2. $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    54 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 hiện bối cảnh. Trong mã của bạn, các đối số này được đóng gói thành một tuple gọi là
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    97 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()
    
    22 đã giành được bất kỳ xử lý ngoại lệ nào.
    expects three arguments with information about any exception that occurred during the execution of the context. In your code, these arguments are packed into a tuple called
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    97 and then ignored, which means that
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 won’t attempt any exception handling.

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

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

[ ... ]

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

* * *
54 không thực hiện bất kỳ xử lý lỗi nào 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 các nhà quản lý bối cảnh là họ đảm bảo gọi
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

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

[ ... ]

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

* * *
54, bất kể bối cảnh như thế nào. Trong ví dụ sau, bạn cố tình tạo lỗi bằng cách chia cho 0:

>>>

>>> import time
>>> time.perf_counter()
32311.48899951

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

Bạn cũng nên lưu ý hai chi tiết tinh tế hơn:

$ python latest_tutorial.py # Python Timer Functions: Three Ways to Monitor Your Code While many developers recognize Python as an effective programming language, pure Python programs may run more slowly than their counterparts in compiled languages like C, Rust, and Java. In this tutorial, you'll learn how to use a Python timer to monitor how quickly your programs are running. [ ... ] ## Read the full article at https://realpython.com/python-timer/ » * * * 53 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() 63, 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() 22, cho phép người dùng liên kết thể hiện 1# latest_tutorial.py 2 3from reader import feed 4 5def main(): 6 """Download and print the latest tutorial from Real Python""" 7 tutorial = feed.get_article(0) 8 print(tutorial) 9 10if __name__ == "__main__": 11 main() 22 với một biến bằng cách sử dụng $ python latest_tutorial.py # Python Timer Functions: Three Ways to Monitor Your Code While many developers recognize Python as an effective programming language, pure Python programs may run more slowly than their counterparts in compiled languages like C, Rust, and Java. In this tutorial, you'll learn how to use a Python timer to monitor how quickly your programs are running. [ ... ] ## Read the full article at https://realpython.com/python-timer/ » * * * 60. Ví dụ: $ python latest_tutorial.py # Python Timer Functions: Three Ways to Monitor Your Code While many developers recognize Python as an effective programming language, pure Python programs may run more slowly than their counterparts in compiled languages like C, Rust, and Java. In this tutorial, you'll learn how to use a Python timer to monitor how quickly your programs are running. [ ... ] ## Read the full article at https://realpython.com/python-timer/ » * * * 93 sẽ tạo biến $ python latest_tutorial.py # Python Timer Functions: Three Ways to Monitor Your Code While many developers recognize Python as an effective programming language, pure Python programs may run more slowly than their counterparts in compiled languages like C, Rust, and Java. In this tutorial, you'll learn how to use a Python timer to monitor how quickly your programs are running. [ ... ] ## Read the full article at https://realpython.com/python-timer/ » * * * 94 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() 22.

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

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

[ ... ]

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

* * *
54 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 hiện bối cảnh. Trong mã của bạn, các đối số này được đóng gói thành một tuple gọi là
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

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

[ ... ]

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

* * *
97 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()
22 đã giành được bất kỳ xử lý ngoại lệ nào.

>>> import time
>>> time.perf_counter()
32311.48899951

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

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

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

[ ... ]

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

* * *
54 không thực hiện bất kỳ xử lý lỗi nào 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 các nhà quản lý bối cảnh là họ đảm bảo gọi
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

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

[ ... ]

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

* * *
54, bất kể bối cảnh như thế nào. Trong ví dụ sau, bạn cố tình tạo lỗi bằng cách chia cho 0:

>>> import time
>>> time.perf_counter()
32311.48899951

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

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()
22 in ra thời gian trôi qua, mặc dù mã bị sập. Nó có thể kiểm tra và ngăn chặn các lỗi trong
$ python latest_tutorial.py
# Python Timer Functions: Three Ways to Monitor Your Code

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

[ ... ]

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

* * *
54. 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 Python Timer

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

Bây giờ, bạn sẽ học cách sử dụng Trình quản lý bối 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()
22 theo thời gian tải xuống các hướng dẫn thực sự của 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()
22 trước đó:

  • Bạn có thể gọi cuộc gọi đến
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    87. Bạn có thể sử dụng Trình quản lý ngữ cảnh để làm cho mã ngắn hơn, đơn giản hơn và dễ đọc hơn:
    You only need one extra line of code to time the execution of a block of code.
  • Mã này không giống như mã ở trên. Sự khác biệt chính là bạn không định nghĩa biến bên ngoài
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    94, giúp giữ cho không gian tên của bạn sạch hơn.
    Invoking the context manager is readable, and you can more clearly visualize the code block that you’re timing.

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

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

Nỗ lực thấp: Bạn chỉ cần thêm một dòng mã để thời gian thực hiện một khối mã.

  1. Khả năng đọc: Gọi trình quản lý bối cảnh có thể đọc được và bạn có thể trực quan hóa rõ hơn khối mã mà bạn có thời gian.

    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()
    
    22 làm trình quản lý ngữ 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()
    
    32 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()
    
    33, trong khi nó có mã dễ nồi hơi. Trong phần tiếp theo, bạn sẽ học cách bạn có thể sử dụng
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 như một người trang trí. Điều này sẽ giúp dễ dàng theo dõi thời gian chạy của các chức năng hoàn chỉnh.

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

  2. 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()
    
    22 của bạn hiện rất linh hoạt. Tuy nhiên, có một trường hợp sử dụng mà bạn có thể hợp lý hóa nó hơn nữa. Nói rằng bạn muốn theo dõi thời gian dành cho một chức năng nhất định trong cơ sở mã của bạn. Sử dụng trình quản lý bối cảnh, về cơ bản bạn có hai tùy chọn khác nhau:

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

    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()
    
    22 mỗi khi bạn gọi chức năng:

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
1decorator. Decorators are powerful constructs that you use to modify the behavior of functions and classes. In this section, you’ll learn a little about how decorators work, how you can extend
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
22 to be a decorator, and how that will simplify timing functions. For a more in-depth explanation of decorators, see Primer on Python Decorators.

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

Bao bọc mã trong chức năng của bạn bên trong Trình quản lý ngữ cảnh:decorator is a function that wraps another function to modify its behavior. This technique is possible because functions are first-class objects in Python. In other words, functions can be assigned to variables and used as arguments to other functions, just like any other object. This gives you a lot of flexibility and is the basis for several of Python’s most powerful features.

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

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

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

>>> import time
>>> time.perf_counter()
32311.48899951

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

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

>>>

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

Dòng

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
20 trang trí tuyên bố in với bộ trang trí
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
18. 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()
77 bằng
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
23 được trả về bởi
>>> import time
>>> time.perf_counter()
32311.48899951

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

>>> time.perf_counter()  # A few seconds later
32315.261320793
18 decorator. Effectively, it replaces
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """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 with
>>> import time
>>> time.perf_counter()
32311.48899951

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

>>> time.perf_counter()  # A few seconds later
32315.261320793
18. The lambda statement represents an anonymous function that does nothing except return
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
45.

Để xác định các nhà trang trí thú vị hơn, bạn cần biết về các chức năng bên trong. Một hàm bên trong là một hàm mà được xác định bên trong một hàm khác. Một cách sử dụng phổ biến của các chức năng bên trong là tạo ra các nhà máy chức năng:inner function is a function that’s defined inside another function. One common use of inner functions is to create function factories:

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

>>> import time
>>> time.perf_counter()
32311.48899951

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

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

>>> time.perf_counter()  # A few seconds later
32315.261320793
28 bên trong
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
26, trong khi
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
26 được xác định bên ngoài
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
27:

>>>

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

Dòng

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
20 trang trí tuyên bố in với bộ trang trí
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
18. 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()
77 bằng
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
23 được trả về bởi
>>> import time
>>> time.perf_counter()
32311.48899951

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

>>>

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

Dòng

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
20 trang trí tuyên bố in với bộ trang trí
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
18. 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()
77 bằng
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
23 được trả về bởi
>>> import time
>>> time.perf_counter()
32311.48899951

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

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

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

  • >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    26 là một hàm bên trong, được xác định bên trong
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    27. Lưu ý rằng bạn có quyền truy cập vào
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    28 bên trong
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    26, trong khi
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    26 được xác định bên ngoài
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    27:
    starts the definition of
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    33 and expects a function as an argument.
  • Thay vào đó, bạn sử dụng
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    27 để tạo các hàm số nhân mới, mỗi hàm dựa trên một yếu tố khác nhau:
    define the inner function
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    35.
  • Tương tự, bạn có thể sử dụng các chức năng bên trong để tạo ra các nhà trang trí. Hãy nhớ rằng, một người trang trí là một hàm trả về một chức năng: returns
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    35.

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
33 là một người trang trí, bởi vì nó là một hàm mong đợi một hàm,
>>> import time
>>> time.perf_counter()
32311.48899951

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

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

>>> time.perf_counter()  # A few seconds later
32315.261320793
33:

  • Dòng 1 bắt đầu định nghĩa của
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    33 và mong đợi một chức năng như một đối số.
    starts the definition of
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    35. This function will replace whichever function
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    33 decorates. The parameters are
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    42 and
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    43, which collect whichever positional and keyword arguments you pass to the function. This gives you the flexibility to use
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    33 on any function.
  • Các dòng 2 đến 5 Xác định hàm bên trong
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    35.
    prints out the name of the decorated function and notes that
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    33 has been applied to it.
  • Dòng 6 trả về
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    35.
    calls
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    34, the function that
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    33 has decorated. It passes on all arguments passed to
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    35.
  • Mô hình này là phổ biến để xác định trang trí. Các phần thú vị là những người xảy ra bên trong hàm bên trong: triples the return value of
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    34 and returns it.

Dòng 2 bắt đầu định nghĩa của

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
35. Hàm này sẽ thay thế bất kỳ hàm nào
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
33 trang trí. Các tham số là
>>> import time
>>> time.perf_counter()
32311.48899951

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

>>> time.perf_counter()  # A few seconds later
32315.261320793
43, 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 cung cấp cho bạn sự linh hoạt để sử dụng
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
33 trên bất kỳ chức năng nào.

>>>

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

Dòng

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
20 trang trí tuyên bố in với bộ trang trí
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
18. 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()
77 bằng
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
23 được trả về bởi
>>> import time
>>> time.perf_counter()
32311.48899951

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

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

>>>

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

[ ... ]
0

>>> import time
>>> time.perf_counter()
32311.48899951

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

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

>>> time.perf_counter()  # A few seconds later
32315.261320793
28 bên trong
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
26, trong khi
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
26 được xác định bên ngoài
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
27:

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

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
27 để 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:

>>>

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

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
33 là một người trang trí, bởi vì nó là một hàm mong đợi một hàm,
>>> import time
>>> time.perf_counter()
32311.48899951

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

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

>>> time.perf_counter()  # A few seconds later
32315.261320793
33:

Dòng 1 bắt đầu định nghĩa của

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
33 và mong đợi một chức năng như một đối số.

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

[ ... ]
2

Các dòng 2 đến 5 Xác định hàm bên trong

>>> import time
>>> time.perf_counter()
32311.48899951

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

>>>

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

[ ... ]
3

Dòng 6 trả về

>>> import time
>>> time.perf_counter()
32311.48899951

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

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

[ ... ]
4

Mô hình này là phổ biến để xác định trang trí. Các phần thú vị là những người xảy ra bên trong hàm bên trong:

Dòng 2 bắt đầu định nghĩa của >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 35. Hàm này sẽ thay thế bất kỳ hàm nào >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 33 trang trí. Các tham số là >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 42 và >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 43, 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 cung cấp cho bạn sự linh hoạt để sử dụng >>> import time >>> time.perf_counter() 32311.48899951 >>> time.perf_counter() # A few seconds later 32315.261320793 33 trên bất kỳ chức năng nào.

Dòng 3 in ra tên của hàm được trang trí và ghi chú rằng

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
33 đã được áp dụng cho nó.

Dòng 4 gọi

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
34, chức năng mà
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
33 đã trang trí. Nó chuyển qua tất cả các đối số được chuyển cho
>>> import time
>>> time.perf_counter()
32311.48899951

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

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

[ ... ]
5

Lưu ý mức độ

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
68 giống với mẫu trước đó mà bạn đã thiết lập cho mã python thời gian. Bạn có thể áp dụng
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
67 như sau:

>>>

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

[ ... ]
6

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

>>>

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

[ ... ]
7

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

>>>

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

[ ... ]
8

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

Bởi vì

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
56 áp dụng khi các chức năng được xác định, bạn cần sử dụng hình thức cơ bản hơn trong các trường hợp này. Một lợi thế của việc sử dụng một bộ trang trí là bạn chỉ cần áp dụng nó một lần và nó sẽ có thời gian cho chức năng mỗi lần:callables. There are many callable types in Python. You can make your own objects callable by defining the special
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
75 method in their class. The following function and class behave similarly:

>>>

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

[ ... ]
9

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

Bởi vì

>>> import time
>>> time.perf_counter()
32311.48899951

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

$ python -m pip install codetiming
0

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
67 làm công việc. Tuy nhiên, theo một nghĩa nào đó, bạn đã trở lại vuông, vì
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
67 không có bất kỳ sự linh hoạt hay thuận tiện 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()
22. 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()
22 của bạn hành động như một người trang trí?

Cho đến nay, bạn đã sử dụng các bộ trang trí làm 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 chính xác. Người trang trí phải được gọi. Có nhiều loại có thể gọi trong Python. Bạn có thể làm cho các đối tượng của riêng bạn có thể gọi được bằng cách xác định phương thức

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
75 đặc biệt trong lớp của họ. Chức năng sau và lớp hoạt động tương tự:

>>>

$ python -m pip install codetiming
1

Ở đây,

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
76 là một ví dụ có thể gọi được và có thể các số vuông, giống như hàm
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
77 trong ví dụ đầu tiên.

Điều này cung cấp cho bạn một cách để thêm khả năng 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()
22 hiện có:

$ python -m pip install codetiming
2

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
75 sử dụng thực tế 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()
22 đã là người quản lý bối cảnh để tận dụng các tiện ích mà bạn đã xác định ở đó. Hãy chắc chắn rằng bạn cũng nhập
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
81 ở đầ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()
34.

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() 22 làm người trang trí:

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

$ python -m pip install codetiming
3

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

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
84. Bạn có thể thêm khả năng trang trí vào các lớp Trình quản lý bối cảnh của mình chỉ bằng cách kế thừa
>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
84:

Khi bạn sử dụng

>>> import time
>>> time.perf_counter()
32311.48899951

>>> time.perf_counter()  # A few seconds later
32315.261320793
84 theo cách này, bạn không cần phải tự mình thực hiện
>>> import time
>>> time.perf_counter()
32311.48899951

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

$ python -m pip install codetiming
4

Sử dụng máy trang trí đồng hồ Python

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

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

  • Nếu bạn so sánh việc thực hiện này với triển khai ban đầu mà không có bất kỳ thời gian nào, thì bạn sẽ nhận thấy rằng sự khác biệt duy nhất là nhập
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 trên dòng 3 và ứng dụng của
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    91 trên dòng 6. Một lợi thế đáng kể của việc sử dụng các nhà trang trí là chúng Thường đơn giản để áp dụng, như bạn thấy ở đây.
    You only need one extra line of code to time the execution of a function.
  • Tuy nhiên, người trang trí vẫn áp dụng cho toàn bộ chức năng. Điều này có nghĩa là mã của bạn đang tính đến thời gian để in hướng dẫn, ngoài thời gian cần tải xuống. Chạy tập lệnh một lần cuối cùng: When you add the decorator, you can note more clearly that your code will time the function.
  • Vị trí của đầu ra thời gian trôi qua là một dấu hiệu nhận biết rằng mã của bạn đang xem xét thời gian cần thiết để in. Như bạn thấy ở đây, mã của bạn in thời gian trôi qua sau hướng dẫn. You only need to add the decorator when the function is defined. Your code will consistently time it every time it’s called.

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()
22 làm người trang trí, bạn sẽ thấy những lợi thế tương tự như bạn đã làm với các nhà quản lý bối cảnh:

Nỗ lực thấp: Bạn chỉ cần thêm một dòng mã để thời gian thực hiện một hàm.

Khả năng đọc: Khi bạn thêm bộ trang trí, bạn có thể lưu ý rõ hơn rằng mã của bạn sẽ có thời gian chức năng.

$ python -m pip install codetiming
5

Tính nhất quán: Bạn chỉ cần thêm bộ trang trí khi hàm được xác định. Mã của bạn sẽ nhất quán thời gian nó mỗi khi nó gọi.

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

>>>

$ python -m pip install codetiming
6

Mã hẹn giờ Python

$ python -m pip install codetiming

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

>>>

$ python -m pip install codetiming
8

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

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

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

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

    $ python -m pip install codetiming
    
    9

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

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

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

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

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

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

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

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

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

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

Một lý do để có một số chức năng là Python đại diện cho thời gian là

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

>>>

>>> import time
>>> type(time)


>>> time.__class__

2

Python sườn

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
10 tuân theo tiêu chuẩn IEEE 754 cho số học dấu phẩy động, cố gắng thể hiện tất cả các số điểm nổi trong 64 bit. Bởi vì có vô số số điểm nổi, bạn có thể thể hiện tất cả chúng với số lượng hữu hạn.

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

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
10 để đại diện cho thời gian.space between the numbers that you can express. This has some consequences when you use a
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
10 to represent time.

Hãy 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")
5. 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 như số giây kể từ một thời điểm nhất định, được gọi là kỷ nguyên. Số lượng đượ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")
5 khá lớn, điều đó 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")
5 không thể đo lường sự khác biệt về nano giây:nanosecond differences:

>>>

Python sườn
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
10 tuân theo tiêu chuẩn IEEE 754 cho số học dấu phẩy động, cố gắng thể hiện tất cả các số điểm nổi trong 64 bit. Bởi vì có vô số số điểm nổi, bạn có thể thể hiện tất cả chúng với số lượng hữu hạn.

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

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

>>>

>>> import time
>>> type(time)


>>> time.__class__

4

Python sườn

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
10 tuân theo tiêu chuẩn IEEE 754 cho số học dấu phẩy động, cố gắng thể hiện tất cả các số điểm nổi trong 64 bit. Bởi vì có vô số số điểm nổi, bạn có thể thể hiện tất cả chúng với số lượng hữu hạn.

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

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

>>>

>>> import time
>>> type(time)


>>> time.__class__

5

Python sườn

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
10 tuân theo tiêu chuẩn IEEE 754 cho số học dấu phẩy động, cố gắng thể hiện tất cả các số điểm nổi trong 64 bit. Bởi vì có vô số số điểm nổi, bạn có thể thể hiện tất cả chúng với số lượng hữu hạn.

>>>

>>> import time
>>> type(time)


>>> time.__class__

6

Python sườn

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
10 tuân theo tiêu chuẩn IEEE 754 cho số học dấu phẩy động, cố gắng thể hiện tất cả các số điểm nổi trong 64 bit. Bởi vì có vô số số điểm nổi, bạn có thể thể hiện tất cả chúng với số lượng hữu hạn.

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

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

Hãy 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")
5. 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 như số giây kể từ một thời điểm nhất định, được gọi là kỷ nguyên. Số lượng đượ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")
5 khá lớn, điều đó 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")
5 không thể đo lường sự khác biệt về nano giây:

>>>

>>> import time
>>> type(time)


>>> time.__class__

7

Python sườn

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
10 tuân theo tiêu chuẩn IEEE 754 cho số học dấu phẩy động, cố gắng thể hiện tất cả các số điểm nổi trong 64 bit. Bởi vì có vô số số điểm nổi, bạn có thể thể hiện tất cả chúng với số lượng hữu hạn.

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

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

  • Hãy 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")
    
    5. 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 như số giây kể từ một thời điểm nhất định, được gọi là kỷ nguyên. Số lượng đượ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")
    
    5 khá lớn, điều đó 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")
    
    5 không thể đo lường sự khác biệt về nano giây:
  • >>> import time
    >>> type(time)
    
    
    >>> time.__class__
    
    
    3
  • Một nanosecond là một tỷ của một giây. Lưu ý rằng việc thêm một nano giây vào
    $ python latest_tutorial.py
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    While many developers recognize Python as an effective programming language,
    pure Python programs may run more slowly than their counterparts in compiled
    languages like C, Rust, and Java. In this tutorial, you'll learn how to use
    a Python timer to monitor how quickly your programs are running.
    
    [ ... ]
    
    ## Read the full article at https://realpython.com/python-timer/ »
    
    * * *
    
    94 không ảnh hưởng đến kết quả.
     1# timer.py
     2
     3import time
     4
     5class TimerError(Exception):
     6    """A custom exception used to report errors in use of Timer class"""
     7
     8class Timer:
     9    def __init__(self):
    10        self._start_time = None
    11
    12    def start(self):
    13        """Start a new timer"""
    14        if self._start_time is not None:
    15            raise TimerError(f"Timer is running. Use .stop() to stop it")
    16
    17        self._start_time = time.perf_counter()
    18
    19    def stop(self):
    20        """Stop the timer, and report the elapsed time"""
    21        if self._start_time is None:
    22            raise TimerError(f"Timer is not running. Use .start() to start it")
    23
    24        elapsed_time = time.perf_counter() - self._start_time
    25        self._start_time = None
    26        print(f"Elapsed time: {elapsed_time:0.4f} seconds")
    
    3, mặt khác, sử dụng một số điểm không xác định theo thời gian làm kỷ nguyên của nó, cho phép nó hoạt động với các số nhỏ hơn và do đó có được độ phân giải tốt hơn:

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

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

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

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

>>>

>>> import time
>>> type(time)


>>> time.__class__

8

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

Một cách tốt hơn là sử dụng thư viện tiêu chuẩn

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

>>> import time
>>> type(time)


>>> time.__class__

9

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

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

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

>>>

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

0

>>> import time
>>> type(time)


>>> time.__class__

8

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

Một cách tốt hơn là sử dụng thư viện tiêu chuẩn

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

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

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

1

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

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

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

2

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

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

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

3

Tìm kiếm tắc nghẽn trong mã của bạn với các trình cấu hình

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

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

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

4

Lệnh này chạy

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

Để sử dụng

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
61, bạn nhập các lệnh tại dấu nhắc. Ở đây bạn có thể thấy hệ thống trợ giúp tích hợp. Thông thường, bạn sẽ sử dụng các lệnh
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
64 và
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
65. Để có được đầu ra sạch hơn,
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
66 có thể hữu ích:bottlenecks you find. You can also use the tool to understand the structure of your code better. For instance, the commands
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
75 and
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
76 will show you which functions call and are called by a given function.

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

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
67), điều đó có nghĩa là mã của bạn tính thời gian khi hàm đã cho được gọi là một hàm khác.

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

5

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

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

Cột tổng thời gian (

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

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

6

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

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

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

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
85.
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
56 có thể cho bạn biết chức năng nào mã của bạn dành nhiều thời gian nhất, nhưng nó đã giành được cho bạn những hiểu biết về dòng bên trong hàm đó là chậm nhất. Đó là nơi mà
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
85 có thể giúp bạn.

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

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
56 để xác định chức năng nào cần điều tra và sau đó chạy
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
85 trên các chức năng đó.
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
85 là một phần của thư viện tiêu chuẩn, vì vậy trước tiên bạn nên làm theo các hướng dẫn cài đặt để thiết lập nó.

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

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
91 bên trong mã nguồn của bạn. Ví dụ: để cấu hình
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
92, bạn thêm phần sau bên trong
 1# latest_tutorial.py
 2
 3from reader import feed
 4
 5def main():
 6    """Download and print the latest tutorial from Real Python"""
 7    tutorial = feed.get_article(0)
 8    print(tutorial)
 9
10if __name__ == "__main__":
11    main()
34:

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

7

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

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
94 ở bất cứ đâu. Thay vào đó, nó tự động thêm vào không gian tên toàn cầu khi bạn chạy trình hồ sơ. Mặc dù vậy, bạn cần phải xóa dòng khi bạn thực hiện định hình. Nếu không, bạn sẽ nhận được một
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
95.

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

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
96, là một phần của gói
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
85:

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

8

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

 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
98. Bạn có thể thấy những kết quả đó bằng cách sử dụng
 1# latest_tutorial.py
 2
 3import time
 4from reader import feed
 5
 6def main():
 7    """Print the latest tutorial from Real Python"""
 8    tic = time.perf_counter()
 9    tutorial = feed.get_article(0)
10    toc = time.perf_counter()
11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
12
13    print(tutorial)
14
15if __name__ == "__main__":
16    main()
85:

>>> type(3)


>>> type(None)


>>> type(print)


>>> type(type)

9

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

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

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

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

Sự kết luận

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

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

     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 trực tiếp cung cấp cho bạn toàn quyền kiểm soát cách thức và thời điểm gọi bộ đếm thời gian.class to keep state and add a user-friendly interface. Classes are very flexible, and using
     1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    22 directly gives you full control over how and when to invoke the timer.

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

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

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

    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    91 là một cách nhanh chóng để theo dõi thời gian chạy mã của bạn.decorator to add behavior to a function. Decorators are concise and compelling, and using
    >>> import time
    >>> time.perf_counter()
    32311.48899951
    
    >>> time.perf_counter()  # A few seconds later
    32315.261320793
    
    91 is a quick way to monitor your code’s runtime.

Bạn cũng đã học được lý do tại sao bạn nên thích

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

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

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

Tài nguyên

Để đi sâu hơn vào các chức năng hẹn giờ Python, hãy xem các tài nguyên này:

  •  1# latest_tutorial.py
     2
     3from reader import feed
     4
     5def main():
     6    """Download and print the latest tutorial from Real Python"""
     7    tutorial = feed.get_article(0)
     8    print(tutorial)
     9
    10if __name__ == "__main__":
    11    main()
    
    23 là bộ đếm thời gian Python có sẵn trên PYPI.
    is the Python timer available on 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")
    
    0 là một bộ đếm hiệu suất cho thời gian chính xác.
    is a performance counter for precise timings.
  •  1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main():
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter()
     9    tutorial = feed.get_article(0)
    10    toc = time.perf_counter()
    11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
    12
    13    print(tutorial)
    14
    15if __name__ == "__main__":
    16    main()
    
    45 là một công cụ để so sánh thời gian chạy của các đoạn mã.
    is a tool for comparing the runtimes of code snippets.
  •  1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main():
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter()
     9    tutorial = feed.get_article(0)
    10    toc = time.perf_counter()
    11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
    12
    13    print(tutorial)
    14
    15if __name__ == "__main__":
    16    main()
    
    56 là một trình hồ sơ để tìm kiếm tắc nghẽn trong các tập lệnh và chương trình.
    is a profiler for finding bottlenecks in scripts and programs.
  •  1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main():
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter()
     9    tutorial = feed.get_article(0)
    10    toc = time.perf_counter()
    11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
    12
    13    print(tutorial)
    14
    15if __name__ == "__main__":
    16    main()
    
    61 là một công cụ dòng lệnh để xem dữ liệu hồ sơ.
    is a command-line tool for looking at profiler data.
  • Kcachegrind là GUI để xem dữ liệu hồ sơ. is a GUI for looking at profiler data.
  •  1# latest_tutorial.py
     2
     3import time
     4from reader import feed
     5
     6def main():
     7    """Print the latest tutorial from Real Python"""
     8    tic = time.perf_counter()
     9    tutorial = feed.get_article(0)
    10    toc = time.perf_counter()
    11    print(f"Downloaded the tutorial in {toc - tic:0.4f} seconds")
    12
    13    print(tutorial)
    14
    15if __name__ == "__main__":
    16    main()
    
    85 là một cấu hình để đo các dòng mã riêng lẻ.
    is a profiler for measuring individual lines of code.
  • $ python latest_tutorial.py
    Downloaded the tutorial in 0.6721 seconds
    # Python Timer Functions: Three Ways to Monitor Your Code
    
    [ ... ]
    
    13 là một trình hồ sơ để theo dõi việc sử dụng bộ nhớ.
    is a profiler for monitoring memory usage.

Có chức năng hẹn giờ trong Python không?

Một bộ đếm thời gian trong Python là một chương trình theo dõi thời gian.Các nhà phát triển Python có thể tạo bộ hẹn giờ với sự trợ giúp của các mô -đun thời gian của Python.Có hai loại hẹn giờ cơ bản: bộ hẹn giờ đếm và những loại đếm ngược.. Python developers can create timers with the help of Python's time modules. There are two basic types of timers: timers that count up and those that count down.

Python có lớp hẹn giờ không?

Lớp hẹn giờ Python được sử dụng để thực hiện thao tác hoặc có một chức năng chạy sau một khoảng thời gian được chỉ định đã trôi qua.Lớp luồng có một lớp con được gọi là hẹn giờ lớp. is used to perform an operation or have a function run after a specified period has passed. The threading class has a subclass called the class timer.

Làm thế nào để Python theo dõi thời gian?

Sử dụng mô -đun thời gian Python để đo thời gian đã trôi qua trong Python, chúng ta cũng có thể sử dụng hàm Timeit (), thực hiện hàm ẩn danh với một số lần thực thi.Nó tạm thời tắt bộ sưu tập rác trong khi tính toán thời gian thực hiện.use the timeit() function, which executes an anonymous function with a number of executions. It temporarily turns off garbage collection while calculating the time of execution.