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
#[cfg(feature = "thread_profiler")]
extern crate time;
#[cfg(feature = "thread_profiler")]
#[macro_use]
extern crate json;
#[cfg(feature = "thread_profiler")]
#[macro_use]
extern crate lazy_static;

#[cfg(feature = "thread_profiler")]
use std::cell::RefCell;
#[cfg(feature = "thread_profiler")]
use std::fs::File;
#[cfg(feature = "thread_profiler")]
use std::io::Write;
#[cfg(feature = "thread_profiler")]
use std::sync::mpsc::{channel, Sender, Receiver};
#[cfg(feature = "thread_profiler")]
use std::sync::Mutex;
#[cfg(feature = "thread_profiler")]
use time::precise_time_ns;

#[cfg(feature = "thread_profiler")]
#[macro_export]
macro_rules! profile_scope {
    ($string:expr) => {
        let _profile_scope = $crate::ProfileScope::new($string);
    }
}

#[cfg(not(feature = "thread_profiler"))]
#[macro_export]
macro_rules! profile_scope {
    ($string:expr) => {
    }
}

#[cfg(feature = "thread_profiler")]
lazy_static! {
    static ref GLOBAL_PROFILER: Mutex<Profiler> = Mutex::new(Profiler::new());
}

#[cfg(feature = "thread_profiler")]
thread_local!(static THREAD_PROFILER: RefCell<Option<ThreadProfiler>> = RefCell::new(None));

#[cfg(feature = "thread_profiler")]
#[derive(Copy, Clone)]
struct ThreadId(usize);

#[cfg(feature = "thread_profiler")]
struct ThreadInfo {
    name: String,
}

#[cfg(feature = "thread_profiler")]
struct Sample {
    tid: ThreadId,
    name: &'static str,
    t0: u64,
    t1: u64,
}

#[cfg(feature = "thread_profiler")]
struct ThreadProfiler {
    id: ThreadId,
    tx: Sender<Sample>,
}

#[cfg(feature = "thread_profiler")]
impl ThreadProfiler {
    fn push_sample(&self,
                   name: &'static str,
                   t0: u64,
                   t1: u64) {
        let sample = Sample {
            tid: self.id,
            name: name,
            t0: t0,
            t1: t1,
        };
        self.tx.send(sample).ok();
    }
}

#[cfg(feature = "thread_profiler")]
struct Profiler {
    rx: Receiver<Sample>,
    tx: Sender<Sample>,
    threads: Vec<ThreadInfo>,
}

#[cfg(feature = "thread_profiler")]
impl Profiler {
    fn new() -> Profiler {
        let (tx, rx) = channel();

        Profiler {
            rx: rx,
            tx: tx,
            threads: Vec::new(),
        }
    }

    fn register_thread(&mut self, name: String) {
        let id = ThreadId(self.threads.len());

        self.threads.push(ThreadInfo {
            name: name,
        });

        THREAD_PROFILER.with(|profiler| {
            assert!(profiler.borrow().is_none());

            let thread_profiler = ThreadProfiler {
                id: id,
                tx: self.tx.clone(),
            };

            *profiler.borrow_mut() = Some(thread_profiler);
        });
    }

    fn write_profile(&self, filename: &str) {
        // Stop reading samples that are written after
        // write_profile() is called.
        let start_time = precise_time_ns();
        let mut data = json::JsonValue::new_array();

        while let Ok(sample) = self.rx.try_recv() {
            if sample.t0 > start_time {
                break;
            }

            let thread_id = self.threads[sample.tid.0].name.as_str();
            let t0 = sample.t0 / 1000;
            let t1 = sample.t1 / 1000;

            data.push(object!{
                "pid" => 0,
                "tid" => thread_id,
                "name" => sample.name,
                "ph" => "B",
                "ts" => t0
            }).unwrap();

            data.push(object!{
                "pid" => 0,
                "tid" => thread_id,
                "ph" => "E",
                "ts" => t1
            }).unwrap();
        }

        let s = json::stringify_pretty(data, 2);
        let mut f = File::create(filename).unwrap();
        f.write_all(s.as_bytes()).unwrap();
    }
}

#[cfg(feature = "thread_profiler")]
pub struct ProfileScope {
    name: &'static str,
    t0: u64,
}

#[cfg(feature = "thread_profiler")]
impl ProfileScope {
    pub fn new(name: &'static str) -> ProfileScope {
        let t0 = precise_time_ns();

        ProfileScope {
            name: name,
            t0: t0,
        }
    }
}

#[cfg(feature = "thread_profiler")]
impl Drop for ProfileScope {
    fn drop(&mut self) {
        let t1 = precise_time_ns();

        THREAD_PROFILER.with(|profiler| {
            match *profiler.borrow() {
                Some(ref profiler) => {
                    profiler.push_sample(self.name, self.t0, t1);
                }
                None => {
                    println!("ERROR: ProfileScope {} on unregistered thread!", self.name);
                }
            }
        });
    }
}

#[cfg(feature = "thread_profiler")]
pub fn write_profile(filename: &str) {
    GLOBAL_PROFILER.lock()
                   .unwrap()
                   .write_profile(filename);
}

#[cfg(feature = "thread_profiler")]
pub fn register_thread_with_profiler(thread_name: String) {
    GLOBAL_PROFILER.lock()
                   .unwrap()
                   .register_thread(thread_name);
}

#[cfg(not(feature = "thread_profiler"))]
pub fn write_profile(_filename: &str) {
    println!("WARN: write_profile was called when the thread profiler is disabled!");
}

#[cfg(not(feature = "thread_profiler"))]
pub fn register_thread_with_profiler(_thread_name: String) {
}