neser 1.2.0

NESER - Nintendo Emulation Systems Engine (Rust). Desktop and WebAssembly frontends.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Shared frame benchmark statistics helpers.

use std::time::Duration;

/// Summary statistics for a frame-timing benchmark run.
#[derive(Debug, Clone, PartialEq)]
pub struct FrameTimingStats {
    /// Number of measured frames.
    pub frames: usize,
    /// Total measured duration.
    pub total: Duration,
    /// Mean frame time in milliseconds.
    pub average_ms: f64,
    /// Median frame time in milliseconds.
    pub p50_ms: f64,
    /// 95th percentile frame time in milliseconds.
    pub p95_ms: f64,
    /// Slowest measured frame in milliseconds.
    pub max_ms: f64,
    /// Effective frames per second.
    pub fps: f64,
}

/// Errors returned while computing benchmark statistics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameTimingStatsError {
    /// No frame timing samples were provided.
    Empty,
    /// The measured frames completed in zero total time.
    ZeroTotal,
}

/// Command-line configuration for a frame benchmark binary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrameBenchmarkConfig {
    /// ROM path to benchmark.
    pub rom_path: String,
    /// Number of frames in each measured run.
    pub frames: usize,
    /// Frames to run before measuring.
    pub warmup_frames: usize,
    /// Additional measured runs for stability reporting.
    pub stability_runs: usize,
    /// Whether the GBA BIOS intro should be skipped before benchmark warmup.
    pub skip_gba_bios_intro: bool,
    /// Whether each stability run should reload the ROM before warmup.
    pub reset_stability_runs: bool,
}

/// Errors returned while parsing benchmark command-line options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameBenchmarkConfigError {
    /// The ROM path argument was omitted.
    MissingRomPath,
    /// A flag that requires a value was missing that value.
    MissingValue { name: &'static str },
    /// A numeric argument could not be parsed.
    InvalidNumber { name: &'static str, value: String },
    /// An unsupported argument was provided.
    UnknownArgument(String),
}

impl FrameBenchmarkConfig {
    /// Parse frame benchmark command-line arguments.
    pub fn parse_args(args: &[String]) -> Result<Self, FrameBenchmarkConfigError> {
        let mut args = args.iter();
        let _program = args.next();
        let rom_path = args
            .next()
            .ok_or(FrameBenchmarkConfigError::MissingRomPath)?
            .clone();

        let mut config = Self {
            rom_path,
            frames: 600,
            warmup_frames: 60,
            stability_runs: 5,
            skip_gba_bios_intro: true,
            reset_stability_runs: true,
        };

        while let Some(arg) = args.next() {
            match arg.as_str() {
                "--frames" => {
                    config.frames = parse_positive_usize_arg(&mut args, "frames")?;
                }
                "--warmup" => {
                    config.warmup_frames = parse_usize_arg(&mut args, "warmup")?;
                }
                "--stability-runs" => {
                    config.stability_runs = parse_usize_arg(&mut args, "stability-runs")?;
                }
                "--include-bios-intro" => {
                    config.skip_gba_bios_intro = false;
                }
                "--skip-bios-intro" => {
                    config.skip_gba_bios_intro = true;
                }
                "--continue-stability-runs" => {
                    config.reset_stability_runs = false;
                }
                _ => return Err(FrameBenchmarkConfigError::UnknownArgument(arg.clone())),
            }
        }

        Ok(config)
    }
}

fn parse_usize_arg<'a, I>(
    args: &mut I,
    name: &'static str,
) -> Result<usize, FrameBenchmarkConfigError>
where
    I: Iterator<Item = &'a String>,
{
    parse_usize_arg_with_validation(args, name, |_| true)
}

fn parse_positive_usize_arg<'a, I>(
    args: &mut I,
    name: &'static str,
) -> Result<usize, FrameBenchmarkConfigError>
where
    I: Iterator<Item = &'a String>,
{
    parse_usize_arg_with_validation(args, name, |value| value > 0)
}

fn parse_usize_arg_with_validation<'a, I, F>(
    args: &mut I,
    name: &'static str,
    validate: F,
) -> Result<usize, FrameBenchmarkConfigError>
where
    I: Iterator<Item = &'a String>,
    F: Fn(usize) -> bool,
{
    let value = args
        .next()
        .ok_or(FrameBenchmarkConfigError::MissingValue { name })?;
    let parsed = value
        .parse()
        .map_err(|_| FrameBenchmarkConfigError::InvalidNumber {
            name,
            value: value.clone(),
        })?;
    if !validate(parsed) {
        return Err(FrameBenchmarkConfigError::InvalidNumber {
            name,
            value: value.clone(),
        });
    }
    Ok(parsed)
}

impl FrameTimingStats {
    /// Compute summary statistics for measured frame durations.
    pub fn from_samples(samples: &[Duration]) -> Result<Self, FrameTimingStatsError> {
        if samples.is_empty() {
            return Err(FrameTimingStatsError::Empty);
        }

        let total = samples.iter().copied().sum();
        if total == Duration::ZERO {
            return Err(FrameTimingStatsError::ZeroTotal);
        }

        let frames = samples.len();
        let total_ms = duration_ms(total);
        let mut sorted_ms: Vec<f64> = samples.iter().map(|&sample| duration_ms(sample)).collect();
        sorted_ms.sort_by(f64::total_cmp);

        Ok(Self {
            frames,
            total,
            average_ms: total_ms / frames as f64,
            p50_ms: percentile(&sorted_ms, 0.50),
            p95_ms: percentile(&sorted_ms, 0.95),
            max_ms: sorted_ms[frames - 1],
            fps: frames as f64 / total.as_secs_f64(),
        })
    }
}

fn duration_ms(duration: Duration) -> f64 {
    duration.as_secs_f64() * 1000.0
}

fn percentile(sorted_samples: &[f64], percentile: f64) -> f64 {
    let index = percentile * (sorted_samples.len() - 1) as f64;
    let lower = index.floor() as usize;
    let upper = index.ceil() as usize;
    let fraction = index - lower as f64;
    sorted_samples[lower] * (1.0 - fraction) + sorted_samples[upper] * fraction
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ms(value: u64) -> Duration {
        Duration::from_millis(value)
    }

    fn assert_close(actual: f64, expected: f64) {
        assert!(
            (actual - expected).abs() < 0.001,
            "expected {expected}, got {actual}"
        );
    }

    #[test]
    fn frame_timing_stats_calculate_percentiles_and_fps() {
        let samples = [ms(12), ms(16), ms(20), ms(10), ms(18)];

        let stats = FrameTimingStats::from_samples(&samples).unwrap();

        assert_eq!(stats.frames, 5);
        assert_eq!(stats.total, ms(76));
        assert_close(stats.average_ms, 15.2);
        assert_close(stats.p50_ms, 16.0);
        assert_close(stats.p95_ms, 19.6);
        assert_close(stats.max_ms, 20.0);
        assert_close(stats.fps, 65.789);
    }

    #[test]
    fn frame_timing_stats_handle_single_sample() {
        let stats = FrameTimingStats::from_samples(&[ms(17)]).unwrap();

        assert_eq!(stats.frames, 1);
        assert_eq!(stats.total, ms(17));
        assert_close(stats.average_ms, 17.0);
        assert_close(stats.p50_ms, 17.0);
        assert_close(stats.p95_ms, 17.0);
        assert_close(stats.max_ms, 17.0);
        assert_close(stats.fps, 58.824);
    }

    #[test]
    fn frame_timing_stats_reject_empty_sample_set() {
        assert_eq!(
            FrameTimingStats::from_samples(&[]),
            Err(FrameTimingStatsError::Empty)
        );
    }

    #[test]
    fn frame_timing_stats_reject_zero_total_time() {
        assert_eq!(
            FrameTimingStats::from_samples(&[Duration::ZERO]),
            Err(FrameTimingStatsError::ZeroTotal)
        );
    }

    #[test]
    fn frame_benchmark_config_uses_gba_title_intro_defaults() {
        let args = vec![
            "gba_frame_bench".to_string(),
            "roms/games/metroid-zero-mission.gba".to_string(),
        ];

        let config = FrameBenchmarkConfig::parse_args(&args).unwrap();

        assert_eq!(config.rom_path, "roms/games/metroid-zero-mission.gba");
        assert_eq!(config.frames, 600);
        assert_eq!(config.warmup_frames, 60);
        assert_eq!(config.stability_runs, 5);
        assert!(config.skip_gba_bios_intro);
        assert!(config.reset_stability_runs);
    }

    #[test]
    fn frame_benchmark_config_parses_overrides() {
        let args = vec![
            "gba_frame_bench".to_string(),
            "rom.gba".to_string(),
            "--frames".to_string(),
            "120".to_string(),
            "--warmup".to_string(),
            "30".to_string(),
            "--stability-runs".to_string(),
            "2".to_string(),
            "--include-bios-intro".to_string(),
        ];

        let config = FrameBenchmarkConfig::parse_args(&args).unwrap();

        assert_eq!(
            config,
            FrameBenchmarkConfig {
                rom_path: "rom.gba".to_string(),
                frames: 120,
                warmup_frames: 30,
                stability_runs: 2,
                skip_gba_bios_intro: false,
                reset_stability_runs: true,
            }
        );
    }

    #[test]
    fn frame_benchmark_config_can_continue_stability_runs_without_resetting() {
        let args = vec![
            "gba_frame_bench".to_string(),
            "rom.gba".to_string(),
            "--continue-stability-runs".to_string(),
        ];

        let config = FrameBenchmarkConfig::parse_args(&args).unwrap();

        assert!(!config.reset_stability_runs);
    }

    #[test]
    fn frame_benchmark_config_rejects_invalid_frame_count() {
        let args = vec![
            "gba_frame_bench".to_string(),
            "rom.gba".to_string(),
            "--frames".to_string(),
            "abc".to_string(),
        ];

        assert_eq!(
            FrameBenchmarkConfig::parse_args(&args),
            Err(FrameBenchmarkConfigError::InvalidNumber {
                name: "frames",
                value: "abc".to_string(),
            })
        );
    }

    #[test]
    fn frame_benchmark_config_rejects_missing_rom_path() {
        let args = vec!["gba_frame_bench".to_string()];

        assert_eq!(
            FrameBenchmarkConfig::parse_args(&args),
            Err(FrameBenchmarkConfigError::MissingRomPath)
        );
    }

    #[test]
    fn frame_benchmark_config_rejects_zero_frame_count() {
        let args = vec![
            "gba_frame_bench".to_string(),
            "rom.gba".to_string(),
            "--frames".to_string(),
            "0".to_string(),
        ];

        assert_eq!(
            FrameBenchmarkConfig::parse_args(&args),
            Err(FrameBenchmarkConfigError::InvalidNumber {
                name: "frames",
                value: "0".to_string(),
            })
        );
    }

    #[test]
    fn frame_benchmark_config_rejects_missing_flag_value() {
        let args = vec![
            "gba_frame_bench".to_string(),
            "rom.gba".to_string(),
            "--frames".to_string(),
        ];

        assert_eq!(
            FrameBenchmarkConfig::parse_args(&args),
            Err(FrameBenchmarkConfigError::MissingValue { name: "frames" })
        );
    }

    #[test]
    fn frame_benchmark_config_rejects_unknown_argument() {
        let args = vec![
            "gba_frame_bench".to_string(),
            "rom.gba".to_string(),
            "--frame".to_string(),
        ];

        assert_eq!(
            FrameBenchmarkConfig::parse_args(&args),
            Err(FrameBenchmarkConfigError::UnknownArgument(
                "--frame".to_string()
            ))
        );
    }

    #[test]
    fn frame_benchmark_config_allows_zero_warmup_and_stability_runs() {
        let args = vec![
            "gba_frame_bench".to_string(),
            "rom.gba".to_string(),
            "--warmup".to_string(),
            "0".to_string(),
            "--stability-runs".to_string(),
            "0".to_string(),
        ];

        let config = FrameBenchmarkConfig::parse_args(&args).unwrap();

        assert_eq!(config.warmup_frames, 0);
        assert_eq!(config.stability_runs, 0);
    }
}