小甲鱼python视频中的程序_[Python]小甲鱼Python视频第044课(魔法方法:简单定制 )课后题及参考解答...

# -*- coding: utf-8 -*-

"""

Created on Tue Mar 19 14:43:06 2019

@author: Administrator

"""

import time

"""

动动手

0. 按照课堂中的程序,如果开始计时的时间是(2022年2月22日16:30:30),停止时间是(2025年1月23日15:30:30),那按照我们用停止时间减开始时间的计算方式就会出现负数,你应该对此做一些转换。

"""

class TimerTest():

def __init__(self):

self.start_time = time.localtime()

self.start_year = self.start_time.tm_year

self.start_mon = self.start_time.tm_mon

self.start_mday = self.start_time.tm_mday

self.start_hour = self.start_time.tm_hour

self.start_min = self.start_time.tm_min

self.start_sec = self.start_time.tm_sec

self.start_wday = self.start_time.tm_wday

self.start_yday = self.start_time.tm_yday

self.start_isdst = self.start_time.tm_isdst

#print(self.start_time)

#print(self.start_hour)

count1 = time.perf_counter()

print('count1 = %f' % count1)

time.sleep(2)

count2 = time.perf_counter()

print('count2 = %f' % count2)

print('count2-count1 = %f' % (count2-count1) )

#tt1 = TimerTest()

"""

1. 相信大家已经意识到不对劲了:为毛一个月一定要31天?不知道有可能也是30天或者29天吗?(上一题我们的答案是假设一个月31天)

没错,如果要正确得到月份的天数,我们还需要考虑是否闰年,还有每月的最大天数,所以太麻烦了……如果我们不及时纠正,我们会在错误的道路上越走越远……

所以,这一次,小甲鱼提出了更优秀的解决方案(Python官方推荐):用 time 模块的 perf_counter() 和 process_time() 来计算,其中 perf_counter() 返回计时器的精准时间(系统的运行时间); process_time() 返回当前进程执行 CPU 的时间总和。

题目:改进我们课堂中的例子,这次使用 perf_counter() 和 process_time() 作为计时器。

另外增加一个 set_timer() 方法,用于设置默认计时器(默认是 perf_counter(),可以通过此方法修改为 process_time())。

"""

class TimerTest1():

def __init__(self):

self.count_func = time.perf_counter

self.start = self.count_func()

self.end = 0

def set_timer(self):

self.count_func = time.process_time

self.start = self.count_func()

self.end = 0

def timerend(self):

self.end = self.count_func()

self.duration = self.end - self.start

print("duration = %f s" % self.duration )

#timeTest1 = TimerTest1()

#time.sleep(3)

#timeTest1.timerend()

#timeTest1.set_timer()

#time.sleep(3)

#timeTest1.timerend()

#perf_counter()

"""

2. 既然咱都做到了这一步,那不如再深入一下。再次改进我们的代码,让它能够统计一个函数运行若干次的时间。

要求一:函数调用的次数可以设置(默认是 1000000 次)

要求二:新增一个 timing() 方法,用于启动计时器

"""

class TimerTest3():

def __init__(self,times = 1000):

self.count_func = time.perf_counter

self.start = 0

self.end = 0

self.times = times

def set_timer(self):

self.count_func = time.process_time

self.start = 0

self.end = 0

def run_times(self):

self.start = self.count_func()

for i in range(self.times):

for j in range(20):

pass

time.sleep(2)

self.end = self.count_func()

self.duration = self.end - self.start

print("duration = %f s" % self.duration )

timeTest3 = TimerTest3(100000*2)

timeTest3.run_times()

timeTest3.set_timer()

timeTest3.run_times()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值