import time def countdown(n): while n > 0: n -= 1 第一种: class Timer: def __init__(self, func=time.perf_counter): self.elapsed = 0.0 self._func = func self._start = None def start(self): if self._start is not None: raise RuntimeError('Already started') self._start = self._func() def stop(self): if self._start is None: raise RuntimeError('Not started') end = self._func() self.elapsed += end - self._start self._start = None def reset(self): self.elapsed = 0.0 @property def running(self): return self._start is not None def __enter__(self): self.start() return self def __exit__(self, *args): self.stop() In [68]: with Timer() as t2: ...: countdown(1000000) ...: print(t2.elapsed) ...: 0.06051115319132805 第二种: In [27]: def profile(func): ...: def wrapper( *args, **kwargs): ...: start = time.time() ...: func(*args, **kwargs) ...: end = time.time() ...: print(end - start) ...: return wrapper ...: In [28]: @profile ...: def countdown(n): ...: while n > 0: ...: n -= 1 ...: In [80]: countdown(1000000) 0.0597081184387207 第三种 ipython In [67]: %timeit countdown(1000000) 10 loops, best of 3: 59.3 ms per loop 第四种 >>> import cProfile >>> def countdown(n): ... while n > 0: ... n -= 1 ... >>> cProfile.run('countdown(1000000)') 4 function calls in 0.068 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.068 0.068 0.068 0.068 <stdin>:1(countdown) 1 0.000 0.000 0.068 0.068 <string>:1(<module>) 1 0.000 0.000 0.068 0.068 {built-in method builtins.exec} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 使用可视化: >>> import cProfile >>> def countdown(n): ... while n > 0: ... n -= 1 ... >>> cProfile.run('countdown(1000000)',"result") 4 function calls in 0.068 seconds snakeviz result