# coding=utf-8
import math
import time
class Timer:
'''
计算程序执行时间
t = Timer()
with t:
执行检测的程序
print t.elapsed
'''
def __init__(self, func=time.perf_counter):
self.elapsed = 0.0
self._func = func
self._start = None
def start(self):
if self._start:
raise RuntimeError('Already started!')
self._start = self._func()
def stop(self):
if not self._start:
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, exc_type, exc_val, exc_tb):
self.stop()
def create(num):
result = []
result_append = result.append
sqrt = math.sqrt
for i in range(num):
result_append(sqrt(i))
if __name__ == '__main__':
t = Timer()
with t:
print('运行状况:{0}'.format(t.running))
create(10000000)
print(t.elapsed)
print('运行状况:{0}'.format(t.running))
Python程序执行时间测试
最新推荐文章于 2024-07-02 20:18:14 发布