4

I have a for loop that iterates over a number and performs some simple calculations. I am trying to figure out how to print out ( or log to file) the current value of 'val' every .5 to 1 second with out having to pause or sleep during the loop. Here is a super simple example

val_list = []

for i in xrange(iterations):
    val = (i*(1/2)) * pi
    val2 = np.linalg.pinv(val)
    # print or write to log val2 after every half second (or 1 second)
    val_list.append(val2)
user982599
  • 975
  • 13
  • 28

3 Answers3

4

Just use time.time to capture the time before starting, then check how long it's been after you calculate val2:

import time

val_list = []

prev_time = time.time()

for i in xrange(iterations):
    val = (i*(1/2)) * pi
    val2 = np.linalg.pinv(val)
    # print or write to log val2 after every half second (or 1 second)
    dt = time.time() - prev_time
    if dt > 1:
        # print or write to log here
        prev_time = time.time()    
    val_list.append(val2)
bj0
  • 7,893
  • 5
  • 38
  • 49
1

You can use time.time():

from time import time as t
val_list = []
nowTime = t()
for i in xrange(iterations):
    val = (i*(1/2)) * pi
    val2 = np.linalg.pinv(val)
    curTime = t()
    if curTime - nowTime >= 0.5:
        #Do your stuff
        nowTime = curTime
    val_list.append(val2)
user1823
  • 1,111
  • 6
  • 19
1

You can achieve this using Threads.

Here's a documentation on how to utilize Threads : https://docs.python.org/3/library/threading.html ( If you're using Python2.7 then change the 3 in the url to a 2 )

Here's a link which is similar to what you want and should also point you in the right direction : Python threading.timer - repeat function every 'n' seconds

Basically you have to create a Thread that will only execute ever n number of seconds. On each iteration it will print the value. The above link should suffice for that. Good luck !

Community
  • 1
  • 1
Meghdeep Ray
  • 5,262
  • 4
  • 34
  • 58