Ask Your Question

Can a loop be made to skip an iteration if the run time exceeds a certain amount?

asked 2020-06-10 06:36:45 +0100

sum8tion gravatar image

updated 2020-06-10 08:32:15 +0100

I apologize if this is a little abstract, but is it possible to create some sort of "for" or "while" loop that will pass to the next iterate if the computation for that specific iterate takes too long?
For example, it could be something along the lines of, for some function/procedure


we have

for n in range(100):

but if for some n in the range, the computation of F(n) takes more than say, 1 minute CPU time, I want it to either just skip to computing F(n+1) and/or print "-1" in place of F(n).
So let's say F(0), F(1), and F(2) all take less than half a second to compute they print just fine, so then n gets set to n=3, and F(3) starts running, but let's say it runs for over a minute, I want it to be that the loop outputs "-1" (or something) and then moves on to computing F(4).

UPDATE: I'd also like to be able, if possible, to print out run times. So that the output would be something like

(F(1), time(1))
(F(2), time(2))
(F(3), times(3))

etc., where time(n) is the amount of time it took to compute F(n).

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted

answered 2020-06-10 08:42:09 +0100

FrédéricC gravatar image

Something like this

            except AlarmInterrupt:
                print("This takes too long.")
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-06-10 06:36:45 +0100

Seen: 204 times

Last updated: Jun 10 '20