while time.time() - start < threshold:
    run_start = time.time()
doSomething()
run_time = time.time() - start
if run_time < best_run:
    best_run = run_time
How to end program running after given time in Python