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]

實現結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM