Ask Your Question
1

How can you determine the duration of a function executing in a loop in Python and use it to decide whether to skip to the next iteration?

asked 2022-04-06 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-01-30 12:00:00 +0000

lakamha gravatar image

You can use the time module in Python to determine the duration of a function executing in a loop. Here's an example:

import time

for i in range(10):
    start_time = time.time()  # Get the start time
    # Execute the function here
    end_time = time.time()  # Get the end time
    duration = end_time - start_time  # Calculate the duration

    if duration > 5:  # If the duration is more than 5 seconds
        continue  # Skip to the next iteration

In this example, the start time is obtained at the beginning of each iteration using the time.time() function. After the function has executed, the end time is obtained and the duration is calculated by subtracting the start time from the end time. If the duration is greater than 5 seconds, the continue statement is used to skip to the next iteration of the loop.

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. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-06 11:00:00 +0000

Seen: 8 times

Last updated: Jan 30 '23