oxiz-sat 0.2.0

High-performance CDCL SAT Solver for OxiZ
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
//! Performance Profiling Utilities
//!
//! Tools for profiling and analyzing SAT solver performance.
//! Includes timers, operation counters, and bottleneck detection.

use crate::prelude::HashMap;
#[allow(unused_imports)]
use crate::prelude::*;
use std::time::{Duration, Instant};

/// A named timer for profiling code sections
#[derive(Debug)]
pub struct ScopedTimer {
    /// Timer name
    name: String,
    /// Start time
    start: Instant,
    /// Whether the timer is running
    running: bool,
    /// Total elapsed time
    elapsed: Duration,
}

impl ScopedTimer {
    /// Create a new timer
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            start: Instant::now(),
            running: true,
            elapsed: Duration::ZERO,
        }
    }

    /// Stop the timer
    pub fn stop(&mut self) {
        if self.running {
            self.elapsed += self.start.elapsed();
            self.running = false;
        }
    }

    /// Restart the timer
    pub fn restart(&mut self) {
        if !self.running {
            self.start = Instant::now();
            self.running = true;
        }
    }

    /// Get the elapsed time
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        if self.running {
            self.elapsed + self.start.elapsed()
        } else {
            self.elapsed
        }
    }

    /// Get the timer name
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }
}

impl Drop for ScopedTimer {
    fn drop(&mut self) {
        if self.running {
            self.stop();
        }
    }
}

/// Profiler for tracking multiple timers and operation counts
#[derive(Debug, Default)]
pub struct Profiler {
    /// Named timers
    timers: HashMap<String, Duration>,
    /// Operation counters
    counters: HashMap<String, u64>,
    /// Active timers
    active: HashMap<String, Instant>,
}

impl Profiler {
    /// Create a new profiler
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Start timing an operation
    pub fn start_timer(&mut self, name: impl Into<String>) {
        let name = name.into();
        self.active.insert(name, Instant::now());
    }

    /// Stop timing an operation
    pub fn stop_timer(&mut self, name: &str) {
        if let Some(start) = self.active.remove(name) {
            let elapsed = start.elapsed();
            *self
                .timers
                .entry(name.to_string())
                .or_insert(Duration::ZERO) += elapsed;
        }
    }

    /// Increment a counter
    pub fn increment(&mut self, name: impl Into<String>) {
        self.increment_by(name, 1);
    }

    /// Increment a counter by a specific amount
    pub fn increment_by(&mut self, name: impl Into<String>, amount: u64) {
        *self.counters.entry(name.into()).or_insert(0) += amount;
    }

    /// Get timer duration
    #[must_use]
    pub fn get_timer(&self, name: &str) -> Option<Duration> {
        self.timers.get(name).copied()
    }

    /// Get counter value
    #[must_use]
    pub fn get_counter(&self, name: &str) -> Option<u64> {
        self.counters.get(name).copied()
    }

    /// Get all timers
    #[must_use]
    pub fn timers(&self) -> &HashMap<String, Duration> {
        &self.timers
    }

    /// Get all counters
    #[must_use]
    pub fn counters(&self) -> &HashMap<String, u64> {
        &self.counters
    }

    /// Clear all profiling data
    pub fn clear(&mut self) {
        self.timers.clear();
        self.counters.clear();
        self.active.clear();
    }

    /// Get total profiled time
    #[must_use]
    pub fn total_time(&self) -> Duration {
        self.timers.values().sum()
    }

    /// Display profiling report
    #[must_use]
    pub fn report(&self) -> String {
        let mut output = String::new();

        output.push_str("═══════════════════════════════════════════════════════════════\n");
        output.push_str("                    PROFILING REPORT                           \n");
        output.push_str("═══════════════════════════════════════════════════════════════\n\n");

        if !self.timers.is_empty() {
            output.push_str("TIMERS:\n");
            let mut timer_vec: Vec<_> = self.timers.iter().collect();
            timer_vec.sort_by(|a, b| b.1.cmp(a.1)); // Sort by duration descending

            let total = self.total_time();

            for (name, duration) in timer_vec {
                let pct = if total > Duration::ZERO {
                    100.0 * duration.as_secs_f64() / total.as_secs_f64()
                } else {
                    0.0
                };

                output.push_str(&format!(
                    "  {:<30} {:>10.3}s  ({:>5.1}%)\n",
                    name,
                    duration.as_secs_f64(),
                    pct
                ));
            }

            output.push_str(&format!("\n  Total Time: {:.3}s\n", total.as_secs_f64()));
            output.push('\n');
        }

        if !self.counters.is_empty() {
            output.push_str("COUNTERS:\n");
            let mut counter_vec: Vec<_> = self.counters.iter().collect();
            counter_vec.sort_by(|a, b| b.1.cmp(a.1)); // Sort by count descending

            for (name, count) in counter_vec {
                output.push_str(&format!("  {:<30} {:>12}\n", name, count));
            }
            output.push('\n');
        }

        output.push_str("═══════════════════════════════════════════════════════════════\n");

        output
    }
}

/// RAII timer that automatically reports on drop
pub struct AutoTimer {
    name: String,
    start: Instant,
}

impl AutoTimer {
    /// Create a new auto timer
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            start: Instant::now(),
        }
    }

    /// Get elapsed time without dropping
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        self.start.elapsed()
    }
}

impl Drop for AutoTimer {
    fn drop(&mut self) {
        tracing::debug!("{}: {:.3}s", self.name, self.start.elapsed().as_secs_f64());
    }
}

/// Macro for creating a scoped timer that logs on drop
#[macro_export]
macro_rules! time_scope {
    ($name:expr) => {
        let _timer = $crate::profiling::AutoTimer::new($name);
    };
}

/// Performance metrics tracker
#[derive(Debug, Default, Clone)]
pub struct PerformanceMetrics {
    /// Total operations performed
    pub total_ops: u64,
    /// Total time spent
    pub total_time: Duration,
    /// Peak operations per second
    pub peak_ops_per_sec: f64,
    /// Average operations per second
    pub avg_ops_per_sec: f64,
}

impl PerformanceMetrics {
    /// Create new metrics
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Update metrics with new data
    pub fn update(&mut self, ops: u64, time: Duration) {
        self.total_ops += ops;
        self.total_time += time;

        let secs = time.as_secs_f64();
        if secs > 0.0 {
            let ops_per_sec = ops as f64 / secs;
            if ops_per_sec > self.peak_ops_per_sec {
                self.peak_ops_per_sec = ops_per_sec;
            }
        }

        let total_secs = self.total_time.as_secs_f64();
        if total_secs > 0.0 {
            self.avg_ops_per_sec = self.total_ops as f64 / total_secs;
        }
    }

    /// Reset all metrics
    pub fn reset(&mut self) {
        self.total_ops = 0;
        self.total_time = Duration::ZERO;
        self.peak_ops_per_sec = 0.0;
        self.avg_ops_per_sec = 0.0;
    }
}

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

    #[test]
    fn test_scoped_timer() {
        let mut timer = ScopedTimer::new("test");
        thread::sleep(Duration::from_millis(10));
        timer.stop();

        assert!(timer.elapsed() >= Duration::from_millis(10));
        assert_eq!(timer.name(), "test");
    }

    #[test]
    fn test_scoped_timer_restart() {
        let mut timer = ScopedTimer::new("test");
        thread::sleep(Duration::from_millis(5));
        timer.stop();

        let first_elapsed = timer.elapsed();

        timer.restart();
        thread::sleep(Duration::from_millis(5));
        timer.stop();

        assert!(timer.elapsed() >= first_elapsed);
    }

    #[test]
    fn test_profiler_timers() {
        let mut profiler = Profiler::new();

        profiler.start_timer("operation1");
        thread::sleep(Duration::from_millis(10));
        profiler.stop_timer("operation1");

        let elapsed = profiler.get_timer("operation1");
        assert!(elapsed.is_some());
        assert!(elapsed.expect("Timer must have elapsed duration") >= Duration::from_millis(10));
    }

    #[test]
    fn test_profiler_counters() {
        let mut profiler = Profiler::new();

        profiler.increment("counter1");
        profiler.increment("counter1");
        profiler.increment_by("counter2", 5);

        assert_eq!(profiler.get_counter("counter1"), Some(2));
        assert_eq!(profiler.get_counter("counter2"), Some(5));
    }

    #[test]
    fn test_profiler_clear() {
        let mut profiler = Profiler::new();

        profiler.increment("counter");
        profiler.start_timer("timer");
        profiler.stop_timer("timer");

        profiler.clear();

        assert_eq!(profiler.counters().len(), 0);
        assert_eq!(profiler.timers().len(), 0);
    }

    #[test]
    fn test_profiler_report() {
        let mut profiler = Profiler::new();

        profiler.start_timer("test_timer");
        profiler.stop_timer("test_timer");
        profiler.increment("test_counter");

        let report = profiler.report();
        assert!(report.contains("PROFILING REPORT"));
        assert!(report.contains("TIMERS:"));
        assert!(report.contains("COUNTERS:"));
    }

    #[test]
    fn test_auto_timer() {
        let timer = AutoTimer::new("test");
        thread::sleep(Duration::from_millis(10));
        assert!(timer.elapsed() >= Duration::from_millis(10));
    }

    #[test]
    fn test_performance_metrics() {
        let mut metrics = PerformanceMetrics::new();

        metrics.update(1000, Duration::from_secs(1));
        assert_eq!(metrics.total_ops, 1000);
        assert!(metrics.avg_ops_per_sec > 0.0);

        metrics.update(2000, Duration::from_secs(1));
        assert_eq!(metrics.total_ops, 3000);
    }

    #[test]
    fn test_performance_metrics_reset() {
        let mut metrics = PerformanceMetrics::new();

        metrics.update(1000, Duration::from_secs(1));
        metrics.reset();

        assert_eq!(metrics.total_ops, 0);
        assert_eq!(metrics.total_time, Duration::ZERO);
    }
}