1

I'm making a simple client/server program in Python 3 and in the client I would like a clock or printout of the running time. I'm trying to make it in a loop that starts at the beginning of the program, but in a thread so the rest of the code keeps going.

    class time_thread():
        def run(self):

            loop = 0

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

This is what I have so far, but it doesn't work. It says:

time_thread has no attribute start()

I'm new to this and haven't used threads before, so I'm not sure how to go about this. Is there a better way?

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
Chenko
  • 35
  • 6

3 Answers3

0

I think this is what you're looking for:

import time, sys

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

First of all , to use Thread module, you have to inherit the class Thread on your class, so you can use their methods like start. To calculate time, you can use 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)   


Just place this

WagnerAlbJr
  • 190
  • 1
  • 12
0

So let's say you define a function elapsed_time such as:

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"),

Then in your program:

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

Should do the job you want to do.

Note: I used python 2.7 so it might be slightly different with 3.x

Ben.T
  • 29,160
  • 6
  • 32
  • 54