use crate::tools::time::{DurationMillis, TimeMillis, MILLIS_IN_MILLISECOND, MILLIS_IN_SECOND};
use crate::tools::types::Pow;
pub struct PowRequiredEstimator {
description: String,
pow_required: Pow,
total_iterations: usize,
best_pow_so_far: Pow,
started_at_millis: TimeMillis,
next_report_millis: TimeMillis,
}
const REPORTING_PERIOD_MILLIS: DurationMillis = MILLIS_IN_SECOND.const_mul(1);
impl PowRequiredEstimator {
pub fn new(started_at_millis: TimeMillis, description: &str, pow_required: Pow) -> Self {
Self {
description: description.to_string(),
pow_required,
total_iterations: 0,
best_pow_so_far: Pow(0),
started_at_millis,
next_report_millis: started_at_millis + REPORTING_PERIOD_MILLIS,
}
}
fn report_large_number(num: usize) -> String {
let num = num as f64;
if num > 1e9 {
return format!("{:.2}B", num / 1e9);
}
if num > 1e6 {
return format!("{:.2}M", num / 1e6);
}
if num > 1e3 {
return format!("{:.2}k", num / 1e3);
}
format!("{}", num)
}
pub fn record_batch_and_estimate(&mut self, current_time_millis: TimeMillis, iterations_in_batch: usize, best_pow_in_batch: Pow) -> Option<String> {
self.total_iterations += iterations_in_batch;
if best_pow_in_batch > self.best_pow_so_far {
self.best_pow_so_far = best_pow_in_batch;
}
if current_time_millis < self.next_report_millis {
return None;
}
self.next_report_millis = current_time_millis + REPORTING_PERIOD_MILLIS;
let elapsed_duration_millis = current_time_millis - self.started_at_millis;
if elapsed_duration_millis < MILLIS_IN_MILLISECOND || self.total_iterations == 0 {
return Some(format!(
"{}: PoW {}/{} bits | {} | {} iters | too early to estimate",
self.description,
self.best_pow_so_far.0,
self.pow_required.0,
elapsed_duration_millis,
Self::report_large_number(self.total_iterations)
));
}
let iterations_per_second = 1000.0 * self.total_iterations as f64 / elapsed_duration_millis.0 as f64;
let expected_total_iterations = (2.0f64).powi(self.pow_required.0 as i32);
let expected_remaining_duration = DurationMillis((1000.0 * expected_total_iterations / iterations_per_second) as i64);
let eta_one_sigma = expected_remaining_duration;
let progress_pct = self.total_iterations as f64 / expected_total_iterations * 100.0;
Some(format!(
"{}: PoW {}/{} bits | {} | {} iters | {}/s | {:.1}% of expected | ETA ~{} \u{00b1}{}",
self.description,
self.best_pow_so_far.0,
self.pow_required.0,
elapsed_duration_millis,
Self::report_large_number(self.total_iterations),
Self::report_large_number(iterations_per_second as usize),
progress_pct,
expected_remaining_duration,
eta_one_sigma,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_estimator() -> PowRequiredEstimator {
PowRequiredEstimator::new(TimeMillis(0), "test", Pow(24))
}
#[test]
fn record_batch_accumulates_iterations_and_tracks_best_pow() {
let mut estimator = make_estimator();
estimator.record_batch_and_estimate(TimeMillis(100), 1024, Pow(10));
assert_eq!(estimator.total_iterations, 1024);
assert_eq!(estimator.best_pow_so_far, Pow(10));
estimator.record_batch_and_estimate(TimeMillis(200), 1024, Pow(8)); assert_eq!(estimator.total_iterations, 2048);
assert_eq!(estimator.best_pow_so_far, Pow(10));
estimator.record_batch_and_estimate(TimeMillis(300), 1024, Pow(15)); assert_eq!(estimator.total_iterations, 3072);
assert_eq!(estimator.best_pow_so_far, Pow(15));
}
#[test]
fn progress_string_contains_key_fields() {
let mut estimator = make_estimator();
let output = estimator.record_batch_and_estimate(TimeMillis(1000), 65536, Pow(18));
assert!(output.is_some());
let output = output.unwrap();
assert!(output.contains("test"), "should include description: {}", output);
assert!(output.contains("18/24"), "should show best/required bits: {}", output);
assert!(output.contains("1s"), "should show elapsed time: {}", output);
assert!(output.contains("65.54"), "should show iteration count: {}", output);
assert!(output.contains("ETA"), "should show ETA: {}", output);
}
#[test]
fn progress_string_before_any_elapsed_time() {
let mut estimator = make_estimator();
let output = estimator.record_batch_and_estimate(TimeMillis(100), 1024, Pow(5));
assert!(output.is_none());
}
#[test]
fn eta_stays_non_negative_past_expected_iterations() {
let mut estimator = PowRequiredEstimator::new(TimeMillis(0), "test", Pow(4));
let output = estimator
.record_batch_and_estimate(TimeMillis(1000), 100, Pow(3))
.expect("should emit a report once the reporting period has elapsed");
let after_eta = output.split("ETA ~").nth(1).expect("output should contain ETA marker");
let eta_str = after_eta.split(' ').next().expect("ETA value should be the first token after the marker");
let eta = DurationMillis::parse(eta_str).expect("ETA value should parse as a DurationMillis");
assert!(eta.0 >= 0, "ETA must be non-negative past expected iterations; got {:?} in {:?}", eta_str, output);
}
}