Skip to content

代码计时

python
import time

class Timer:
    def __enter__(self):
        self.start_time = time.time()
        return self
        
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.elapsed_time = time.time() - self.start_time
        
    def __str__(self):
        return f"Elapsed time: {self.elapsed_time:.3f} seconds"

if __name__ == "__main__":
    
    with Timer() as timer:
        main()

    print(timer)

Released under the MIT License.