torsh-profiler 0.1.2

Performance profiling and monitoring for ToRSh
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Attribute-based profiling support
//!
//! This module provides function decorators and attribute-like functionality for automatic profiling.
//! While Rust doesn't have decorators like Python, we provide similar functionality through wrapper functions.

use crate::cpu::ProfileScope;
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use std::any::type_name;
use std::time::Instant;

/// Trait for automatic profiling of methods
pub trait ProfiledMethod<Args, Return> {
    /// Execute the method with automatic profiling
    fn profiled(self, name: Option<&str>, category: Option<&str>) -> Return;
}

/// Wrapper for functions that enables automatic profiling
pub struct ProfiledFunction<F> {
    func: F,
    name: String,
    category: String,
    enabled: bool,
}

impl<F> ProfiledFunction<F> {
    /// Create a new profiled function wrapper
    pub fn new(func: F, name: String, category: String) -> Self {
        Self {
            func,
            name,
            category,
            enabled: true,
        }
    }

    /// Enable/disable profiling for this function
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Check if profiling is enabled for this function
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }
}

impl<F, R> ProfiledFunction<F>
where
    F: FnOnce() -> R,
{
    /// Execute the function with profiling
    pub fn call(self) -> R {
        if self.enabled {
            let _guard = ProfileScope::simple(self.name, self.category);
            (self.func)()
        } else {
            (self.func)()
        }
    }
}

impl<F> ProfiledFunction<F> {
    /// Execute the function with one argument and profiling
    pub fn call_with_arg<A, R>(self, arg: A) -> R
    where
        F: FnOnce(A) -> R,
    {
        if self.enabled {
            let _guard = ProfileScope::simple(self.name, self.category);
            (self.func)(arg)
        } else {
            (self.func)(arg)
        }
    }

    /// Execute the function with two arguments and profiling
    pub fn call_with_args<A, B, R>(self, arg1: A, arg2: B) -> R
    where
        F: FnOnce(A, B) -> R,
    {
        if self.enabled {
            let _guard = ProfileScope::simple(self.name, self.category);
            (self.func)(arg1, arg2)
        } else {
            (self.func)(arg1, arg2)
        }
    }
}

/// Attribute configuration for profiling
#[derive(Debug, Clone)]
pub struct ProfileAttribute {
    /// Name of the profiling event
    pub name: Option<String>,
    /// Category of the profiling event
    pub category: Option<String>,
    /// Whether to include stack traces
    pub stack_trace: bool,
    /// Whether to track memory allocations
    pub track_memory: bool,
    /// Whether to count FLOPS (for tensor operations)
    pub count_flops: bool,
    /// Custom metadata to include
    pub metadata: std::collections::HashMap<String, String>,
    /// Sampling rate (1 = profile every call, 10 = profile every 10th call)
    pub sample_rate: usize,
    /// Minimum duration threshold to record (in microseconds)
    pub min_duration_us: u64,
}

impl Default for ProfileAttribute {
    fn default() -> Self {
        Self {
            name: None,
            category: Some("function".to_string()),
            stack_trace: false,
            track_memory: false,
            count_flops: false,
            metadata: std::collections::HashMap::new(),
            sample_rate: 1,
            min_duration_us: 0,
        }
    }
}

impl ProfileAttribute {
    /// Create a new profile attribute with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the profiling name
    pub fn with_name<S: Into<String>>(mut self, name: S) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the profiling category
    pub fn with_category<S: Into<String>>(mut self, category: S) -> Self {
        self.category = Some(category.into());
        self
    }

    /// Enable stack trace collection
    pub fn with_stack_trace(mut self) -> Self {
        self.stack_trace = true;
        self
    }

    /// Enable memory tracking
    pub fn with_memory_tracking(mut self) -> Self {
        self.track_memory = true;
        self
    }

    /// Enable FLOPS counting
    pub fn with_flops_counting(mut self) -> Self {
        self.count_flops = true;
        self
    }

    /// Add custom metadata
    pub fn with_metadata<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Set sampling rate
    pub fn with_sample_rate(mut self, rate: usize) -> Self {
        self.sample_rate = rate.max(1);
        self
    }

    /// Set minimum duration threshold
    pub fn with_min_duration_us(mut self, min_us: u64) -> Self {
        self.min_duration_us = min_us;
        self
    }
}

/// Function attribute registry for managing profiling attributes
pub struct AttributeRegistry {
    attributes: std::collections::HashMap<String, ProfileAttribute>,
    global_enabled: bool,
}

impl Default for AttributeRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl AttributeRegistry {
    /// Create a new attribute registry
    pub fn new() -> Self {
        Self {
            attributes: std::collections::HashMap::new(),
            global_enabled: true,
        }
    }

    /// Register a function with profiling attributes
    pub fn register<S: Into<String>>(&mut self, function_name: S, attr: ProfileAttribute) {
        self.attributes.insert(function_name.into(), attr);
    }

    /// Get profiling attributes for a function
    pub fn get_attributes(&self, function_name: &str) -> Option<&ProfileAttribute> {
        self.attributes.get(function_name)
    }

    /// Enable/disable all profiling
    pub fn set_enabled(&mut self, enabled: bool) {
        self.global_enabled = enabled;
    }

    /// Check if profiling is globally enabled
    pub fn is_enabled(&self) -> bool {
        self.global_enabled
    }

    /// Check if a specific function should be profiled
    pub fn should_profile(&self, function_name: &str, call_count: usize) -> bool {
        if !self.global_enabled {
            return false;
        }

        if let Some(attr) = self.attributes.get(function_name) {
            call_count % attr.sample_rate == 0
        } else {
            false
        }
    }
}

/// Global attribute registry
static mut GLOBAL_REGISTRY: Option<AttributeRegistry> = None;
static REGISTRY_INIT: std::sync::Once = std::sync::Once::new();

/// Get the global attribute registry
pub fn get_registry() -> &'static mut AttributeRegistry {
    unsafe {
        REGISTRY_INIT.call_once(|| {
            GLOBAL_REGISTRY = Some(AttributeRegistry::new());
        });
        GLOBAL_REGISTRY
            .as_mut()
            .expect("GLOBAL_REGISTRY should be initialized by call_once")
    }
}

/// Wrapper function that applies profiling attributes to any function
pub fn with_profiling<F, R>(function_name: &str, func: F) -> R
where
    F: FnOnce() -> R,
{
    let registry = get_registry();

    // Check if we should profile this call
    static CALL_COUNTS: Lazy<Mutex<std::collections::HashMap<String, usize>>> =
        Lazy::new(|| Mutex::new(std::collections::HashMap::new()));
    let call_count = {
        let mut counts = CALL_COUNTS.lock();
        let count = counts.entry(function_name.to_string()).or_insert(0);
        *count += 1;
        *count
    };

    if !registry.should_profile(function_name, call_count) {
        return func();
    }

    let attr = registry.get_attributes(function_name);

    // Determine profiling name and category
    let profile_name = attr
        .and_then(|a| a.name.as_ref())
        .cloned()
        .unwrap_or_else(|| function_name.to_string());

    let profile_category = attr
        .and_then(|a| a.category.as_ref())
        .cloned()
        .unwrap_or_else(|| "function".to_string());

    let start_time = Instant::now();

    // Set up profiling scope
    let _guard = ProfileScope::simple(profile_name.clone(), profile_category.clone());

    // Execute the function
    let result = func();

    let duration = start_time.elapsed();
    let duration_us = duration.as_micros() as u64;

    // Check minimum duration threshold
    if let Some(attr) = attr {
        if duration_us < attr.min_duration_us {
            return result;
        }
    }

    result
}

/// Helper macro for creating profiled function wrappers
#[macro_export]
macro_rules! profiled_fn {
    ($name:expr, $func:expr) => {
        $crate::attributes::ProfiledFunction::new($func, $name.to_string(), "function".to_string())
    };
    ($name:expr, $category:expr, $func:expr) => {
        $crate::attributes::ProfiledFunction::new($func, $name.to_string(), $category.to_string())
    };
}

/// Attribute-like macro for profiling functions
#[macro_export]
macro_rules! profile_attribute {
    // Basic profiling
    (#[profile]) => {
        let _attr_guard = $crate::cpu::ProfileScope::simple(
            format!("{}::{}", module_path!(), function_name!()),
            "function".to_string(),
        );
    };

    // Profiling with custom name
    (#[profile(name = $name:expr)]) => {
        let _attr_guard =
            $crate::cpu::ProfileScope::simple($name.to_string(), "function".to_string());
    };

    // Profiling with custom name and category
    (#[profile(name = $name:expr, category = $category:expr)]) => {
        let _attr_guard =
            $crate::cpu::ProfileScope::simple($name.to_string(), $category.to_string());
    };

    // Profiling with sampling
    (#[profile(sample_rate = $rate:expr)]) => {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static CALL_COUNT: AtomicUsize = AtomicUsize::new(0);

        let call_num = CALL_COUNT.fetch_add(1, Ordering::Relaxed);
        let _attr_guard = if call_num % $rate == 0 {
            Some($crate::cpu::ProfileScope::simple(
                format!("{}::{}", module_path!(), function_name!()),
                "sampled_function".to_string(),
            ))
        } else {
            None
        };
    };
}

/// Method profiling wrapper for structs
pub trait ProfiledStruct {
    /// Execute a method with profiling
    fn profiled_method<F, R>(&self, method_name: &str, func: F) -> R
    where
        F: FnOnce(&Self) -> R,
    {
        let type_name = type_name::<Self>();
        let full_name = format!("{type_name}::{method_name}");

        let _guard = ProfileScope::simple(full_name, "method".to_string());
        func(self)
    }

    /// Execute a mutable method with profiling
    fn profiled_method_mut<F, R>(&mut self, method_name: &str, func: F) -> R
    where
        F: FnOnce(&mut Self) -> R,
    {
        let type_name = type_name::<Self>();
        let full_name = format!("{type_name}::{method_name}");

        let _guard = ProfileScope::simple(full_name, "method".to_string());
        func(self)
    }
}

/// Blanket implementation for all types
impl<T> ProfiledStruct for T {}

/// Conditional profiling based on feature flags or runtime conditions
pub struct ConditionalProfiler {
    condition: Box<dyn Fn() -> bool + Send + Sync>,
    fallback_enabled: bool,
}

impl ConditionalProfiler {
    /// Create a new conditional profiler
    pub fn new<F>(condition: F) -> Self
    where
        F: Fn() -> bool + Send + Sync + 'static,
    {
        Self {
            condition: Box::new(condition),
            fallback_enabled: true,
        }
    }

    /// Create a conditional profiler that only profiles in debug mode
    pub fn debug_only() -> Self {
        Self::new(|| cfg!(debug_assertions))
    }

    /// Create a conditional profiler based on an environment variable
    pub fn env_var(var_name: &str) -> Self {
        let var_name = var_name.to_string();
        Self::new(move || {
            std::env::var(&var_name)
                .map(|v| v == "1" || v.to_lowercase() == "true")
                .unwrap_or(false)
        })
    }

    /// Create a conditional profiler based on a feature flag
    pub fn feature_flag(feature: &str) -> Self {
        let enabled = feature == "profiling";
        Self::new(move || enabled)
    }

    /// Execute a function with conditional profiling
    pub fn profile<F, R>(&self, name: &str, category: &str, func: F) -> R
    where
        F: FnOnce() -> R,
    {
        if (self.condition)() {
            let _guard = ProfileScope::simple(name.to_string(), category.to_string());
            func()
        } else {
            func()
        }
    }
}

/// Helper for async function profiling
pub struct AsyncProfiler;

impl AsyncProfiler {
    /// Profile an async function
    pub async fn profile<F, Fut, R>(name: &str, category: &str, func: F) -> R
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = R>,
    {
        let _guard = ProfileScope::simple(name.to_string(), category.to_string());
        func().await
    }
}

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

    #[test]
    fn test_profile_attribute_creation() {
        let attr = ProfileAttribute::new()
            .with_name("test_function")
            .with_category("test")
            .with_stack_trace()
            .with_memory_tracking()
            .with_sample_rate(5)
            .with_min_duration_us(1000);

        assert_eq!(attr.name, Some("test_function".to_string()));
        assert_eq!(attr.category, Some("test".to_string()));
        assert!(attr.stack_trace);
        assert!(attr.track_memory);
        assert_eq!(attr.sample_rate, 5);
        assert_eq!(attr.min_duration_us, 1000);
    }

    #[test]
    fn test_attribute_registry() {
        let mut registry = AttributeRegistry::new();

        let attr = ProfileAttribute::new()
            .with_name("test_func")
            .with_category("test");

        registry.register("my_function", attr);

        let retrieved = registry.get_attributes("my_function");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, Some("test_func".to_string()));
    }

    #[test]
    fn test_sampling() {
        let mut registry = AttributeRegistry::new();

        let attr = ProfileAttribute::new().with_sample_rate(3);
        registry.register("sampled_func", attr);

        // Should profile on calls 3, 6, 9, etc.
        assert!(!registry.should_profile("sampled_func", 1));
        assert!(!registry.should_profile("sampled_func", 2));
        assert!(registry.should_profile("sampled_func", 3));
        assert!(!registry.should_profile("sampled_func", 4));
        assert!(!registry.should_profile("sampled_func", 5));
        assert!(registry.should_profile("sampled_func", 6));
    }

    #[test]
    fn test_profiled_function() {
        let func = || {
            std::thread::sleep(Duration::from_millis(1));
            42
        };

        let profiled = ProfiledFunction::new(func, "test_func".to_string(), "test".to_string());
        let result = profiled.call();
        assert_eq!(result, 42);
    }

    #[test]
    fn test_with_profiling() {
        let result = with_profiling("test_function", || {
            std::thread::sleep(Duration::from_millis(1));
            "success"
        });
        assert_eq!(result, "success");
    }

    #[test]
    fn test_profiled_struct() {
        struct TestStruct {
            value: i32,
        }

        let mut test_struct = TestStruct { value: 42 };

        let result = test_struct.profiled_method("get_value", |s| s.value);
        assert_eq!(result, 42);

        test_struct.profiled_method_mut("set_value", |s| {
            s.value = 100;
        });
        assert_eq!(test_struct.value, 100);
    }

    #[test]
    fn test_conditional_profiler() {
        let profiler = ConditionalProfiler::new(|| true);

        let result = profiler.profile("test_op", "test", || {
            std::thread::sleep(Duration::from_millis(1));
            "conditional_result"
        });
        assert_eq!(result, "conditional_result");

        // Test with false condition
        let profiler = ConditionalProfiler::new(|| false);
        let result = profiler.profile("test_op", "test", || {
            std::thread::sleep(Duration::from_millis(1));
            "not_profiled"
        });
        assert_eq!(result, "not_profiled");
    }

    #[test]
    fn test_debug_only_profiler() {
        let profiler = ConditionalProfiler::debug_only();

        let result = profiler.profile("debug_op", "debug", || "debug_result");
        assert_eq!(result, "debug_result");
    }

    #[tokio::test]
    async fn test_async_profiler() {
        let result = AsyncProfiler::profile("async_test", "async", || async {
            tokio::time::sleep(Duration::from_millis(1)).await;
            "async_success"
        })
        .await;

        assert_eq!(result, "async_success");
    }

    #[test]
    fn test_profiled_fn_macro() {
        let func = || {
            std::thread::sleep(Duration::from_millis(1));
            "macro_result"
        };

        let profiled = profiled_fn!("macro_test", func);
        let result = profiled.call();
        assert_eq!(result, "macro_result");
    }
}