timedsleep(delay=None, start=None, verbose=False)[source]#

Pause for the specified amount of time, taking into account how long other operations take.

This function is usually used in a loop; it works like time.sleep(), but subtracts time taken by the other operations in the loop so that each loop iteration takes exactly delay amount of time. Note: since time.sleep() has a minimum overhead (about 2e-4 seconds), below this duration, no pause will occur.

  • delay (float) – time, in seconds, to wait for

  • start (float) – if provided, the start time

  • verbose (bool) – whether to print details


# Example for a long(ish) computation
import numpy as np
for i in range(10):
    sc.timedsleep('start') # Initialize
    n = int(2*np.random.rand()*1e6) # Variable computation time
    for j in range(n):
        tmp = np.random.rand()
    sc.timedsleep(1, verbose=True) # Wait for one second per iteration including computation time

# Example illustrating more accurate timing
import time
n = 1000

with sc.timer():
    for i in range(n):
# Elapsed time: 1.01 s

with sc.timer():
    for i in range(n):
# Elapsed time: 1.21 s

New in version 3.0.0: “verbose” False by default; more accurate overhead calculation