1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_camel_case_types)]
13 use std::cell::{RefCell, Cell};
14 use std::collections::HashMap;
15 use std::ffi::CString;
17 use std::hash::{Hash, BuildHasher};
18 use std::iter::repeat;
20 use std::time::{Duration, Instant};
24 // The name of the associated type for `Fn` return types
25 pub const FN_OUTPUT_NAME: &'static str = "Output";
27 // Useful type to use with `Result<>` indicate that an error has already
28 // been reported to the user, so no need to continue checking.
29 #[derive(Clone, Copy, Debug)]
30 pub struct ErrorReported;
32 thread_local!(static TIME_DEPTH: Cell<usize> = Cell::new(0));
34 /// Read the current depth of `time()` calls. This is used to
35 /// encourage indentation across threads.
36 pub fn time_depth() -> usize {
37 TIME_DEPTH.with(|slot| slot.get())
40 /// Set the current depth of `time()` calls. The idea is to call
41 /// `set_time_depth()` with the result from `time_depth()` in the
43 pub fn set_time_depth(depth: usize) {
44 TIME_DEPTH.with(|slot| slot.set(depth));
47 pub fn time<T, F>(do_it: bool, what: &str, f: F) -> T where
50 if !do_it { return f(); }
52 let old = TIME_DEPTH.with(|slot| {
58 let start = Instant::now();
60 let dur = start.elapsed();
62 let mem_string = match get_resident() {
64 let mb = n as f64 / 1_000_000.0;
65 format!("; rss: {}MB", mb.round() as usize)
67 None => "".to_owned(),
69 println!("{}time: {}{}\t{}",
70 repeat(" ").take(old).collect::<String>(),
71 duration_to_secs_str(dur),
75 TIME_DEPTH.with(|slot| slot.set(old));
80 // Hack up our own formatting for the duration to make it easier for scripts
81 // to parse (always use the same number of decimal places and the same unit).
82 pub fn duration_to_secs_str(dur: Duration) -> String {
83 const NANOS_PER_SEC: f64 = 1_000_000_000.0;
84 let secs = dur.as_secs() as f64 +
85 dur.subsec_nanos() as f64 / NANOS_PER_SEC;
87 format!("{:.3}", secs)
90 pub fn to_readable_str(mut val: usize) -> String {
91 let mut groups = vec![];
93 let group = val % 1000;
98 groups.push(format!("{}", group));
101 groups.push(format!("{:03}", group));
110 pub fn record_time<T, F>(accu: &Cell<Duration>, f: F) -> T where
113 let start = Instant::now();
115 let duration = start.elapsed();
116 accu.set(duration + accu.get());
120 // Like std::macros::try!, but for Option<>.
122 macro_rules! option_try(
123 ($e:expr) => (match $e { Some(e) => e, None => return None })
128 fn get_resident() -> Option<usize> {
133 let mut f = option_try!(File::open("/proc/self/statm").ok());
134 let mut contents = String::new();
135 option_try!(f.read_to_string(&mut contents).ok());
136 let s = option_try!(contents.split_whitespace().nth(field));
137 let npages = option_try!(s.parse::<usize>().ok());
142 fn get_resident() -> Option<usize> {
145 type HANDLE = *mut u8;
149 #[allow(non_snake_case)]
150 struct PROCESS_MEMORY_COUNTERS {
152 PageFaultCount: DWORD,
153 PeakWorkingSetSize: size_t,
154 WorkingSetSize: size_t,
155 QuotaPeakPagedPoolUsage: size_t,
156 QuotaPagedPoolUsage: size_t,
157 QuotaPeakNonPagedPoolUsage: size_t,
158 QuotaNonPagedPoolUsage: size_t,
159 PagefileUsage: size_t,
160 PeakPagefileUsage: size_t,
162 type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS;
163 #[link(name = "psapi")]
165 fn GetCurrentProcess() -> HANDLE;
166 fn GetProcessMemoryInfo(Process: HANDLE,
167 ppsmemCounters: PPROCESS_MEMORY_COUNTERS,
170 let mut pmc: PROCESS_MEMORY_COUNTERS = unsafe { mem::zeroed() };
171 pmc.cb = mem::size_of_val(&pmc) as DWORD;
172 match unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) } {
174 _ => Some(pmc.WorkingSetSize as usize),
178 pub fn indent<R, F>(op: F) -> R where
182 // Use in conjunction with the log post-processor like `src/etc/indenter`
183 // to make debug output more readable.
186 debug!("<< (Result = {:?})", r);
190 pub struct Indenter {
191 _cannot_construct_outside_of_this_module: (),
194 impl Drop for Indenter {
195 fn drop(&mut self) { debug!("<<"); }
198 pub fn indenter() -> Indenter {
200 Indenter { _cannot_construct_outside_of_this_module: () }
203 pub trait MemoizationMap {
207 /// If `key` is present in the map, return the valuee,
208 /// otherwise invoke `op` and store the value in the map.
210 /// NB: if the receiver is a `DepTrackingMap`, special care is
211 /// needed in the `op` to ensure that the correct edges are
212 /// added into the dep graph. See the `DepTrackingMap` impl for
214 fn memoize<OP>(&self, tcx: TyCtxt, key: Self::Key, op: OP) -> Self::Value
215 where OP: FnOnce() -> Self::Value;
218 impl<K, V, S> MemoizationMap for RefCell<HashMap<K,V,S>>
219 where K: Hash+Eq+Clone, V: Clone, S: BuildHasher
224 fn memoize<OP>(&self, _tcx: TyCtxt, key: K, op: OP) -> V
225 where OP: FnOnce() -> V
227 let result = self.borrow().get(&key).cloned();
229 Some(result) => result,
232 self.borrow_mut().insert(key, result.clone());
240 pub fn path2cstr(p: &Path) -> CString {
241 use std::os::unix::prelude::*;
243 let p: &OsStr = p.as_ref();
244 CString::new(p.as_bytes()).unwrap()
247 pub fn path2cstr(p: &Path) -> CString {
248 CString::new(p.to_str().unwrap()).unwrap()
253 fn test_to_readable_str() {
254 assert_eq!("0", to_readable_str(0));
255 assert_eq!("1", to_readable_str(1));
256 assert_eq!("99", to_readable_str(99));
257 assert_eq!("999", to_readable_str(999));
258 assert_eq!("1_000", to_readable_str(1_000));
259 assert_eq!("1_001", to_readable_str(1_001));
260 assert_eq!("999_999", to_readable_str(999_999));
261 assert_eq!("1_000_000", to_readable_str(1_000_000));
262 assert_eq!("1_234_567", to_readable_str(1_234_567));