Python简单示例-time模块的应用

1、输入一个列表(里面元素是整型),遍历列表中的数字作为延迟的秒数,延迟后输出当前时间

import time
#使用map函数实现键盘输入列表
lst=list(map(int,input("输入空格间隔数字:").split()))
#写一个循环,遍历列表中的内容
for i in lst:
    #使用sleep使程序延迟
    time.sleep(i)
    #使用strftime将时间转换成正常的格式
    time_now=time.strftime("%Y-%m-%d%H:%M:%S ",time.localtime())
    print(time_now)

运行结果:(延迟4秒得出结果)

输入空格间隔数字:1 2 3
2020-12-0719:42:33 
2020-12-0719:42:35 
2020-12-0719:42:38 

解析:
list(map(int,input(“输入空格间隔数字:”).split())),该语句通过map可以实现某个函数的批量调用

int指int()函数,强制类型转换

**input().split()**会把输入的字符串数据用空格分隔开。如果输入1 2 3,语句会把它分隔为[‘1’,‘2’,‘3’],map()会调用3次int()函数:int(‘1’),int(‘2’),int(‘3’),然后map()还把int()函数调用的返回值收集起来,把[‘1’,‘2’,‘3’]转换成[1,2,3]

2、分别使用for循环和while循环计算整数1~1000的和,并且比较二者的用时,如果for循环用时短则输出"for win!",如果while循环用时短则输出“while win!”,如果两个循环用时相等则输出“draw!”

import time
#输出当前的时间
print("比赛开始于:",time.strftime("%Y-%m-%d%H:%M:%S",time.localtime()),"\n")
#记录当前系统最高精度的时间
start_time=time.perf_counter()
#设置一个计数器
count_for=0
#定义一个for循环累加的代码
for i in range(1,1001):
    #每循环一次,都加上当前i的值
    count_for+=i
print("for循环计算的结果为:{}".format(count_for))
#记录结束的时间
end_time=time.perf_counter()
#计算花费的时间
cost_time1=end_time-start_time
#花费的总时长
print("for循环花费的总时间是:{}秒".format(cost_time1))

start_time=time.perf_counter()
count_while=0
#定义一个while循环累加的代码
i=1
while i<1001:
    count_while+=i
    i+=1
print("while循环计算的结果为:{}".format(count_while))
end_time=time.perf_counter()
cost_time2=end_time-start_time
print("while循环计算的结果为:{}秒".format(cost_time2))
print("for循环花费的时间-while循环花费的时间为:{}秒".format(cost_time1-cost_time2))
if cost_time1-cost_time2>0:
    print('\nwhile win!')
elif cost_time1-cost_time2<0:
    print('\nfor win!')
else:
    print('\ndraw!')

运行结果:

比赛开始于: 2020-12-0720:08:15 

for循环计算的结果为:500500
for循环花费的总时间是:0.00014849999999999933while循环计算的结果为:500500
while循环计算的结果为:0.00020440000000000041for循环花费的时间-while循环花费的时间为:-5.590000000000109e-05for win!

time.**perf_counter()**方法具有最高可用分辨率的时钟,以测量短持续时间
perf_counter()会包含sleep()函数产生的睡眠时间,并且是系统范围的时间

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值