time.clock() 被移除,可用time.perf_counter() 或 time.process_time()替代


前言

Python time.clock() 函數以浮點數計算的秒數返回當前的CPU時間。用來衡量不同程序的耗時,比time.time()更有用。
這個需要注意,在不同的系統上含義不同。在UNIX系統上,它返回的是"進程時間",它是用秒表示的浮點數(時間戳)。而在WINDOWS中,第一次調用,返回的是進程運行的實際時間。
而第二次之后的調用是自第一次調用以后到現在的運行時間。(實際上是以WIN32上QueryPerformanceCounter()為基礎,它比毫秒表示更為精確)


摘抄來源:RUNOOB.COM

3.8及之后的版本,使用time.clock()將報錯

  import time
  scale = 50
  print('執行開始'.center(scale//2,'*'))
  t = time.clock()
  for i in range(scale+1):
        a = '*'*i
        b = '.'*(scale-i)
        c = (i/scale)*100
        t -= time.clock()
        print('\r{:^3.0f}%[{}->{}]{:.2f}秒'.format(c,a,b,-t),\
            end='')
        time.sleep(0.05)
  print('\n'+'執行結束'.center(scale//2,'*'))
  
  '''以下為報錯內容
  d:\py\111\1.py:4: DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
    t = time.clock()
  d:\py\111\1.py:9: DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
    t -= time.clock()
  '''

可以替換為 time.perf_counter()

  import time
  scale = 50
  print('執行開始'.center(scale//2,'*'))
  t = time.perf_counter()
  for i in range(scale+1):
        a = '*'*i
        b = '.'*(scale-i)
        c = (i/scale)*100
        t -= time.perf_counter()
        print('\r{:^3.0f}%[{}->{}]{:.2f}秒'.format(c,a,b,-t),\
            end='')
        time.sleep(0.05)
  print('\n'+'執行結束'.center(scale//2,'*'))      
  '''以下為運行結果
  ***********執行開始**********
  100%[**************************************************->]65.35秒
  ***********執行結束**********
  '''


免責聲明!

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



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