循环剩余执行时间预估结果异常,寻求解决方案
Fixing Your Loop's Estimated Remaining Time Calculation
Hey there! I see exactly why your remaining time estimate is way off—let's break down the issue and fix it step by step.
The Problem with Your Current Code
Right now, you're calculating remaining as the total time elapsed since the loop started multiplied by the number of remaining iterations. That's not right because:
- On the first iteration,
execution_timeis just the tiny amount of time it took to run that first loop pass. Multiply that by 999, and you get a huge overestimate (hence the minute-level times at the start). - As the loop progresses,
execution_timebecomes the total time from the start to that point. Multiplying that by remaining iterations would mean you're assuming every future iteration will take as long as the entire loop has taken so far—definitely not accurate!
The Correct Approach
You need to calculate the average time per completed iteration, then multiply that by the number of remaining iterations. This gives a much more realistic estimate that gets better as the loop runs.
Fixed Code
from datetime import datetime start = datetime.now() total_iterations = 1000 # Use a variable for easier maintenance for i in range(total_iterations): # Your calculation logic goes here progress = i + 1 # Since range starts at 0, progress is i+1 current_elapsed = datetime.now() - start # Calculate average time per iteration (no division by zero since progress starts at 1) avg_time_per_iter = current_elapsed / progress remaining_time = avg_time_per_iter * (total_iterations - progress) print(f"Progress: {progress}/{total_iterations}, estimated {remaining_time} time remaining")
Extra Tips for Better Estimates
- If your iterations have variable runtime (some take longer than others), you could use a rolling average of the last N iterations instead of the total average. For example, track the last 10 iteration times and average those—this makes the estimate adapt faster to changes in runtime.
- Using
f-stringsmakes your print statement cleaner and easier to read, as shown above.
内容的提问来源于stack exchange,提问作者Alessandro Ceccarelli
相关产品推荐
相关产品推荐

