第一个完整的python代码(计时器)

import time as t

class MyTimer():

    def __init__(self):
        self.unit=['年','月','天','小时','分钟','秒']
        self.prompt="未开始计时。。。"
        self.lasted=[] 
        self.begin=0
        self.end=0
    
    def __str__(self):
        return self.prompt

    __repr=__str__

    def __add__(self,other):
        prompt="总共运行了"
        result=[]
        for index in range(6):
            result.append(self.lasted[index]+other.lasted[index])
            if result[index]:
               prompt+=(str(result[index])+self.unit[index])
        return prompt
    
    
    #开始计时
    def start(self):
        self.begin=t.localtime()
        self.prompt="提示:请先调用stop()停止计时"
        print("计时开始。。。")

    #停止计时
    def stop(self):
        if not self.begin:
            print("提示:请先调用start()进行计时")
        else :
            self.end=t.localtime()
            self._calc()
            print("计时结束。。。")

    ##内部方法,计算运行时间
    def _calc(self):
        self.lasted=[]
        self.prompt="总共运行了"
        for index in range(6):
            self.lasted.append(self.end[index]-self.begin[index])
            if self.lasted[index]:
                self.prompt+=(str(self.lasted[index])+self.unit[index])

        print(self.prompt)
        


  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果你需要同时管理多个缓存数据并且需要针对每个缓存数据设置不同的超时时间,可以使用 Python 的 `threading.Timer` 类实现多个计时器。 以下是一个示例代码: ```python import datetime import threading cache = {} def get_data(key): if key in cache: data, timer = cache[key] timer.cancel() # 取消之前的计时器 return data else: return None def set_data(key, data, timeout): if key in cache: cache[key][1].cancel() # 取消之前的计时器 timer = threading.Timer(timeout, lambda: del_data(key)) cache[key] = (data, timer) timer.start() def del_data(key): del cache[key] ``` 在这个示例代码中,我们使用了一个字典 `cache` 来存储缓存数据和对应的计时器。在 `get_data` 函数中,我们先取消之前的计时器,然后返回缓存数据。在 `set_data` 函数中,我们首先检查字典中是否已经存在该缓存数据,如果存在则先取消之前的计时器。然后创建一个新的计时器,并将其存储到字典中。计时器会在指定的超时时间后调用 `del_data` 函数来删除缓存数据。 需要注意的是,`threading.Timer` 类使用单独的线程来执行计时器回调函数,因此如果你需要大量使用计时器,可能会导致系统资源占用过多。此外,由于 Python 的全局解释器锁(GIL)限制,可能会影响多线程并发执行的效率。如果你需要更高效的实现方式,可以考虑使用 Python 的第三方库,比如 `gevent` 或 `asyncio`。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值