【问题标题】:How to make a loop that calculates running time?如何制作一个计算运行时间的循环?
【发布时间】:2018-03-23 13:56:49
【问题描述】:

我正在 Python 3 中制作一个简单的客户端/服务器程序,在客户端中我想要一个时钟或运行时间的打印输出。我试图让它在一个从程序开头开始的循环中,但在一个线程中,所以其余的代码继续运行。

    class time_thread():
        def run(self):

            loop = 0

            while (zetime > -1):
                print(zetime);
                zetime = zetime + 1;
    time_thread.start()
zetime = 0

这是我目前所拥有的,但它不起作用。它说:

time_thread 没有属性 start()

我是新手,之前没有使用过线程,所以我不知道该怎么做。有没有更好的办法?

【问题讨论】:

标签: python multithreading loops time


【解决方案1】:

我想这就是你要找的东西:

import time, sys

zetime = 0
while (zetime > -1):
    sys.stdout.write("\r" + str(zetime))
    sys.stdout.flush()
    time.sleep(1)
    zetime = zetime + 1;

【讨论】:

    【解决方案2】:

    首先,要使用 Thread 模块,你必须在你的类上继承 Thread 类,所以你可以使用它们的方法,比如 start。 要计算时间,可以使用 datetime。

    
    from datetime import datetime
    from time import sleep
    
    start_time  = datetime.now()   
    sleep(5) # code that you want to calculate.
    end_time = datetime.now()   
    print(end_time - start_time)   
    
    
    

    放这个

    【讨论】:

      【解决方案3】:

      假设您定义了一个函数 elapsed_time,例如:

      import time, sys
      def elapsed_time(time_start):
          ''' time_start: a time.time()
              Goal: print the elapsed time since time_start '''
          # Allow to stop the counting once bool_time = False in the main program
          global bool_elapsed_time
          # loop while the condition 
          while bool_elapsed_time == True:
              # Note: erase and write below does not work in spyder but in a shell yes
              print ("Elapsed time: {} seconds".format(int(time.time() - time_start))),
              sys.stdout.flush()
              print ("\r"),
              time.sleep(1)
          # erase the line with elapsed time to clean the shell at the end
          sys.stdout.flush()
          print ("\r"),
      

      然后在你的程序中:

      import threading
      bool_elapsed_time = True
      t = threading.Thread(name='child procs', target=elapsed_time, args=(time.time(),))
      t.start()
      ## Here add the job you want to do as an example:
      time.sleep(10)
      bool_elapsed_time = False #to stop the elapsed time printing
      

      应该做你想做的工作。

      注意:我使用的是 python 2.7,所以它可能与 3.x 略有不同

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-04
        • 2016-09-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多