Creating an alarm in seconds Python - python-3.x

I am trying to code a function that recognizes when X amount of seconds has passed without pausing the program, so without using time.sleep. How would I be able to do that by using the unix timestamp? So for the code below it would print 5 seconds has passed for every 5 seconds that passes.
import time
X = 5
TIME = time.time()

Check this will help you avoid using time.sleep() and your code will be iterating till the time reaches next X seconds
import time
startTime = time.time()
X = 5
timeDif = 0
while timeDif < X:
currentTime = time.time()
timeDif = currentTime - startTime

Related

Python 3+ How can i display a countdown timer in terminal with exactly milliseconds

Hello I'm trying to make a countdown timer with exactly milliseconds and print it to terminal.
input : a float value like (9.200)
output : countdown time for 9 seconds 200 milliseconds
like below site tool
https://www.online-stopwatch.com/countdown-timer/
even i could try to print time in milliseconds format but the time is not exactly. Maybe it's a not good question but Is there any way to do it?. Thank you guys so much.
I tried to search about this case but can't match any
Below code is what i got from internet but time is not correct and i need a countdown timer a above site had. Thanks
from __future__ import print_function, division
import time , datetime
counter, timestr = 0, ''
print(time.asctime())
t0 = time.time()
try:
while True:
sectime, ff = divmod(counter,1000)
mintime, ss = divmod(sectime,60)
hh, mm = divmod(mintime, 60)
print(''.join('\b' for c in timestr), end='')
timestr='%02i:%02i:%02i.%2s' % (hh, mm, ss, ff)
print(timestr, end='')
time.sleep(.1)
counter += 1
except KeyboardInterrupt:
t0 = time.time() - t0
print('\nCounter seconds: %.1f, time.time seconds: %.1f'
% (counter/10.0, t0 ))
You haven't mentioned what exactly didn't work for you, but I'll attempt to give a general answer anyway. You could try something like this -
# Saved as timer.py
import sys, time
## Create the variable _TIME from sys.argv or wherever, make sure it is a valid float, > 0, etc etc
## Depends on how you expect input
_TIME = 5 # Just for example, remove this
while _TIME > 0:
m, s = divmod(_TIME, 60)
h, m = divmod(m, 60)
print(f"\r{int(h)}".rjust(3,'0'), f"{int(m)}".rjust(2,'0'),
f"{s:.3f}".rjust(5,'0'), sep=':', end='')
_TIME -= 0.001
time.sleep(0.001)
else:
print("\r Completed ! ")
Then use $ python3 timer.py 5 or something like that in your terminal.
Notes :
This may not be accurate, especially if your print statement is slow in the the terminal. See What is the best way to repeatedly execute a function every x seconds? for several better alternatives since accuracy may be important here.
In some terminals/GUIs, \r may not actually move the cursor back to the start of the line as expected. You might not be able to really do anything about this, that's a problem with the terminal app.
Edit:
Right after I posted this, I saw that you'd updated your question. The code vou've shared definitely has problems - its a lot for me to completely explain here. The most obvious is time.sleep(0.1) waits 100ms, not 1, so your timer won't ever update that often. Try reading other sources on how to accomplish what you want.

Game of life is running slow

I am trying to simulate n-dimensional game of life for first t=6 time steps. My Nim code is a straightforward port from Python and it works correctly but instead of the expected speedup, for n=4, t=6 it takes 2 seconds to run, which is order of magnitude slower than my CPython version. Why is my code so slow? What can I do to speed it up? I am compiling with -d:release and --opt:speed
I represent each point in space with a single 64bit integer.
That is, I map (x_0, x_1, ..., x_{n-1}) to sum x_i * 32^i. I can do that since I know that after 6 time steps each coordinate -15<=x_i<=15 so I have no overflow.
The rules are:
alive - has 2 or 3 alive neigbours: stays alive
- different number of them: becomes alive
dead - has 3 alive neighbours: becomes alive
- else: stays dead
Below is my code. The critical part is the proc nxt which gets set of active cells and outputs set of active cells next time step. This proc is called 6 times. The only thing I'm interested in is the number of alive cells.
I run the code on the following input:
.##...#.
.#.###..
..##.#.#
##...#.#
#..#...#
#..###..
.##.####
..#####.
Code:
import sets, tables, intsets, times, os, math
const DIM = 4
const ROUNDS = 6
const REG_SIZE = 5
const MAX_VAL = 2^(REG_SIZE-1)
var grid = initIntSet()
# Inits neighbours
var neigbours: seq[int]
proc initNeigbours(base,depth: int) =
if depth == 0:
if base != 0:
neigbours.add(base)
else:
initNeigbours(base*2*MAX_VAL-1, depth-1)
initNeigbours(base*2*MAX_VAL+0, depth-1)
initNeigbours(base*2*MAX_VAL+1, depth-1)
initNeigbours(0,DIM)
echo neigbours
# Calculates next iteration:
proc nxt(grid: IntSet): IntSet =
var counting: CountTable[int]
for x in grid:
for dx in neigbours:
counting.inc(x+dx)
for x, count in counting.pairs:
if count == 3 or (count == 2 and x in grid):
result.incl(x)
# Loads input
var row = 0
while true:
var line = stdin.readLine
if line == "":
break
for col in 0..<line.len:
if line[col] == '#':
grid.incl((row-MAX_VAL)*2*MAX_VAL + col-MAX_VAL)
inc row
# Run computation
let time = cpuTime()
for i in 1..ROUNDS:
grid = nxt(grid)
echo "Time taken: ", cpuTime() - time
echo "Result: ", grid.len
discard stdin.readLine
Your code runs in my computer in about 0.02:
Time taken: 0.020875947
Result: 2276
Time taken: 0.01853268
Result: 2276
Time taken: 0.021355269
Result: 2276
I changed the part where the input is read to this:
# Loads input
var row = 0
let input = open("input.txt")
for line in input.lines:
for i, col in line:
if col == '#':
grid.incl((row-MAX_VAL)*2*MAX_VAL + i-MAX_VAL)
inc row
input.close()
But it shouldn't impact the performance, it just looks better to my eyes. I compiled with:
nim c -d:danger script.nim
Using Nim 1.4.2. -d:danger is the flag for maximum speed before entering deeper waters.
But even compiling in debug mode:
$ nim c -r script.nim
Time taken: 0.07699487199999999
Result: 2276
Way faster than 2 seconds. There has to be other problem in your end. Sorry for the non-answer.

How to run a while loop in the background of my program?

So I'm making a Quiz for a school project and I want to start a timer at the start of the Quiz which will be stopped at the end and printed the time took for the player to complete the Quiz, I put the Timer that I created at the start but my program gets stuck at the 'While loop' and doesn't continue with the program.
Heres the beginning of my code:
import time
score = 0
lives = 3
o = 1
timer = 0
while o == 1:
time.sleep(1)
timer += 1
I add 1 to 'o' just before the Quiz ends so I can print out the time taken but I can get past the start
Your While loop isnt comparing the value of 'o'. Use == not = and check.

While loop in Python to notify when it reaches a certain time

I don't know how to use the while loop in Python so that it will notify me if reaches a certain time.
from datetime import datetime
import time
import os
now = datetime.now()
end = 1
while x == 1:
global end
if now.minute == *TIME*:
end = 0
print ("Notification")
My interpretation of what you asked:
import datetime, time
def delay(end_time):
while datetime.datetime.now() < end_time:
time.sleep(.1) # wait .1 seconds before continuing
start_time = datetime.datetime.now()
end_time = start_time + datetime.timedelta(seconds=60) # add 60 seconds
delay(end_time)
print('done')
I was a little confused by what you were doing. Something to notice is the use of less than, instead of equals in the while loop. If you use equals it will only exit if the code is evaluated at the exact time you specified (this is very unlikely to ever happen, so you will be stuck in the loop forever). But with less than you can exit the first time it notices you have waited long enough. You could replace all of this with just time.sleep(60).

fast way to convert datetime to string

I want to know if there is faster way to convert a datetime to a string besides datestr.
datetime is inserted every other lines in my main function (including all of its dependency). I need time at that line of code is executed.
I think my only option is to convert datetime to string faster.
t = datetime('now');
DateString = datestr(t);
I profiled and it seems it is called 12570846 times. It takes 16030.021s in total.
My goal of doing this is get the current time when the line is executed and to match with other information that I get from other program with timestamps. I match two files (one from this MATLAB code and one from my other program) with time stamps.
One way you could do this would be to compare the current time to the time the previous time through the loop. You should only recompute the datestring value if it's different. But we can actually go a step further, because the output of datestr (as you're calling it) only shows seconds. So we can actually ignore microsecond differences.
Example Using now (~128 Seconds)
Below I have an example loop that caches the date string representation. It compares the serial date (in seconds) to the date for which the last date string was generated. Only if it's different is the date string updated.
% Number of seconds in a day to convert the serial date number
secperday = 60 * 60 * 24;
% Store the current time as a reference
lasttime = now;
datestring = datestr(lasttime);
for k = 1:12570846
N = now;
seconds = round(N * secperday);
if ~isequal(lasttime, seconds)
% Update the cache
lasttime = seconds;
datestring = datestr(N);
end
% Use datestring however you want
disp(datestring)
end
Example using clock (~24 seconds)
Another option is to use clock which will give you the different date components in a vector. You can round the last element which represents seconds and milliseconds. By rounding it you suppress the milliseconds. This method seems to be a faster approach.
N = clock;
% Remove milliseconds
N(end) = round(N(end));
lasttime = N;
datestring = datestr(N);
for k = 1:12570846
N = clock;
% Ignore milliseconds
N(end) = round(N(end));
if ~isequal(N, lasttime)
lasttime = N;
datestring = datestr(N);
end
disp(datestring)
end
Funtion-Based Solution
If you want to get the current time as a date string at several points within your code, it is likely much better to create a function which will wrap this functionality. Here is an example of such a function.
function str = getDateString()
% Use persistent variables to cache the current value
persistent lasttime datestring
% Get the current time
thistime = clock;
% Truncate the milliseconds
thistime(end) = floor(thistime(end));
% See if the time has changed since the last time we called this
if ~isequal(thistime, lasttime)
lasttime = thistime;
% Update the cached string reprsentation
datestring = datestr(thistime);
end
str = datestring;
end
You can then call this from anywhere within your code to get the date string and it will only be computed when necessary.
If your loop time is pretty short you might convert the date time every 10th loop or something like that if it will be close enough.

Resources