Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - printing something in a for loop every n seconds

Tags:

python

loops

math

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)
like image 213
user982599 Avatar asked Oct 14 '25 09:10

user982599


2 Answers

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)
like image 86
bj0 Avatar answered Oct 16 '25 21:10

bj0


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)
like image 28
user1823 Avatar answered Oct 16 '25 21:10

user1823



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!