ab.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. //! Diagnostics: switches that change while the title runs, so that one run
  2. //! measures both sides in the same scene. `VICTORY_AB=<seconds>,<switch>[,<switch>..]`:
  3. //! every so many seconds, at a present, the next phase begins; switch number
  4. //! n is on in the phases whose number has bit n, so that all combinations
  5. //! come one after another, again and again. Each phase's frame times are
  6. //! logged at its end (the frames of its first second left out). A switch
  7. //! named here does not go by its own variable any more.
  8. use std::sync::atomic::{AtomicU32, Ordering::Relaxed};
  9. use std::sync::{Mutex, OnceLock};
  10. struct Asked {
  11. seconds: f64,
  12. switches: Vec<String>,
  13. }
  14. fn parse(text: &str) -> Option<Asked> {
  15. let mut parts = text.split(',').map(str::trim);
  16. let seconds = parts.next()?.parse::<f64>().ok().filter(|s| *s > 1.0)?;
  17. let switches: Vec<String> = parts.filter(|s| !s.is_empty()).map(str::to_string).collect();
  18. (!switches.is_empty() && switches.len() <= 8).then_some(Asked { seconds, switches })
  19. }
  20. fn asked() -> Option<&'static Asked> {
  21. static ASKED: OnceLock<Option<Asked>> = OnceLock::new();
  22. ASKED.get_or_init(|| parse(&std::env::var("VICTORY_AB").ok()?)).as_ref()
  23. }
  24. /// The switches that are on now, a bit each.
  25. static BITS: AtomicU32 = AtomicU32::new(0);
  26. /// Whether `switch` is on now, if it is one of those that change.
  27. pub(crate) fn pick(switch: &str) -> Option<bool> {
  28. bit(switch).map(on)
  29. }
  30. /// The number of `switch` among those that change.
  31. pub(crate) fn bit(switch: &str) -> Option<u32> {
  32. Some(asked()?.switches.iter().position(|s| s == switch)? as u32)
  33. }
  34. /// Whether the switch of that number is on now.
  35. pub(crate) fn on(bit: u32) -> bool {
  36. BITS.load(Relaxed) >> bit & 1 != 0
  37. }
  38. /// What the run has seen of the phase under way.
  39. struct Phase {
  40. started: std::time::Instant,
  41. number: u64,
  42. began: std::time::Instant,
  43. last: std::time::Instant,
  44. drawn: u64,
  45. frames: Vec<f32>,
  46. draws: u64,
  47. }
  48. /// The frames' mean, median and nine tenths.
  49. fn summary(frames: &mut [f32]) -> (f32, f32, f32) {
  50. if frames.is_empty() {
  51. return (0.0, 0.0, 0.0);
  52. }
  53. let mean = frames.iter().sum::<f32>() / frames.len() as f32;
  54. frames.sort_by(f32::total_cmp);
  55. (mean, frames[frames.len() / 2], frames[frames.len() * 9 / 10])
  56. }
  57. /// The title's present ends on this thread. `change`: called when another
  58. /// phase begins, before any switch changes, with what `switch` is and what it
  59. /// will be.
  60. pub(crate) fn presented(change: impl Fn(&str, bool, bool)) {
  61. let Some(asked) = asked() else {
  62. return;
  63. };
  64. static PHASE: Mutex<Option<Phase>> = Mutex::new(None);
  65. let now = std::time::Instant::now();
  66. let drawn = crate::draw::drawn();
  67. let mut phase = PHASE.lock().unwrap_or_else(|e| e.into_inner());
  68. let p = phase.get_or_insert_with(|| Phase {
  69. started: now,
  70. number: 0,
  71. began: now,
  72. last: now,
  73. drawn,
  74. frames: Vec::new(),
  75. draws: 0,
  76. });
  77. if (now - p.began).as_secs_f64() > 1.0 {
  78. p.frames.push((now - p.last).as_secs_f32() * 1000.0);
  79. p.draws += drawn.saturating_sub(p.drawn);
  80. }
  81. (p.last, p.drawn) = (now, drawn);
  82. let number = ((now - p.started).as_secs_f64() / asked.seconds) as u64;
  83. if number == p.number {
  84. return;
  85. }
  86. let bits = |number: u64| (number % (1 << asked.switches.len())) as u32;
  87. let (was, will) = (bits(p.number), bits(number));
  88. let (mean, median, most) = summary(&mut p.frames);
  89. let on: Vec<&str> = asked.switches.iter().enumerate().filter(|(n, _)| was >> n & 1 != 0).map(|(_, s)| s.as_str()).collect();
  90. tracing::info!(
  91. "A/B phase {} bits {was} on [{}]: {} frames, mean {mean:.1} ms, median {median:.1}, p90 {most:.1}, {:.0} draws a frame",
  92. p.number,
  93. on.join(" "),
  94. p.frames.len(),
  95. p.draws as f64 / p.frames.len().max(1) as f64
  96. );
  97. for (n, switch) in asked.switches.iter().enumerate() {
  98. change(switch, was >> n & 1 != 0, will >> n & 1 != 0);
  99. }
  100. BITS.store(will, Relaxed);
  101. (p.number, p.began, p.draws) = (number, now, 0);
  102. p.frames.clear();
  103. }
  104. #[cfg(test)]
  105. mod tests {
  106. use super::*;
  107. #[test]
  108. fn switches_and_seconds_are_read_and_frames_summed_up() {
  109. let a = parse("10, VICTORY_A,VICTORY_B").unwrap();
  110. assert_eq!((a.seconds, a.switches), (10.0, vec!["VICTORY_A".to_string(), "VICTORY_B".to_string()]));
  111. assert!(parse("10").is_none());
  112. assert!(parse("x,VICTORY_A").is_none());
  113. assert!(parse("0,VICTORY_A").is_none());
  114. assert_eq!(summary(&mut [30.0, 10.0, 20.0]), (20.0, 20.0, 30.0));
  115. assert_eq!(summary(&mut []), (0.0, 0.0, 0.0));
  116. assert_eq!(pick("VICTORY_NONE_SUCH"), None);
  117. }
  118. }