Skip to content

Commit

Permalink
auto merge of rust-lang#18858 : alexcrichton/rust/remove-time, r=jakub
Browse files Browse the repository at this point in the history
This commit deprecates the entire libtime library in favor of the
externally-provided libtime in the rust-lang organization. Users of the
`libtime` crate as-is today should add this to their Cargo manifests:

    [dependencies.time]
    git = "https://github.com/rust-lang/time"

To implement this transition, a new function `Duration::span` was added to the
`std::time::Duration` time. This function takes a closure and then returns the
duration of time it took that closure to execute. This interface will likely
improve with `FnOnce` unboxed closures as moving in and out will be a little
easier.

Due to the deprecation of the in-tree crate, this is a:

[breaking-change]

cc rust-lang#18855, some of the conversions in the `src/test/bench` area may have been a
little nicer with that implemented
  • Loading branch information
bors committed Nov 12, 2014
2 parents 7a86aa8 + fcd05ed commit 5745e41
Show file tree
Hide file tree
Showing 22 changed files with 336 additions and 273 deletions.
1 change: 0 additions & 1 deletion src/librustc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ extern crate rustc_llvm;
extern crate rustc_back;
extern crate serialize;
extern crate rbml;
extern crate time;
#[phase(plugin, link)] extern crate log;
#[phase(plugin, link)] extern crate syntax;

Expand Down
16 changes: 9 additions & 7 deletions src/librustc/metadata/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,16 +228,16 @@ use util::fs;

use std::c_str::ToCStr;
use std::cmp;
use std::collections::hash_map::{Occupied, Vacant};
use std::collections::{HashMap, HashSet};
use std::io::fs::PathExtensions;
use std::io;
use std::ptr;
use std::slice;
use std::string;
use std::time::Duration;

use std::collections::{HashMap, HashSet};
use std::collections::hash_map::{Occupied, Vacant};
use flate;
use time;

pub struct CrateMismatch {
path: Path,
Expand Down Expand Up @@ -691,11 +691,13 @@ impl ArchiveMetadata {

// Just a small wrapper to time how long reading metadata takes.
fn get_metadata_section(is_osx: bool, filename: &Path) -> Result<MetadataBlob, String> {
let start = time::precise_time_ns();
let ret = get_metadata_section_imp(is_osx, filename);
let mut ret = None;
let dur = Duration::span(|| {
ret = Some(get_metadata_section_imp(is_osx, filename));
});
info!("reading {} => {}ms", filename.filename_display(),
(time::precise_time_ns() - start) / 1000000);
return ret;
dur.num_milliseconds());
return ret.unwrap();;
}

fn get_metadata_section_imp(is_osx: bool, filename: &Path) -> Result<MetadataBlob, String> {
Expand Down
18 changes: 3 additions & 15 deletions src/librustc/middle/trans/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,6 @@ use syntax::visit::Visitor;
use syntax::visit;
use syntax::{ast, ast_util, ast_map};

use time;

local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)

pub fn with_insn_ctxt(blk: |&[&'static str]|) {
Expand Down Expand Up @@ -138,23 +136,16 @@ pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
pub struct StatRecorder<'a, 'tcx: 'a> {
ccx: &'a CrateContext<'a, 'tcx>,
name: Option<String>,
start: u64,
istart: uint,
}

impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String)
-> StatRecorder<'a, 'tcx> {
let start = if ccx.sess().trans_stats() {
time::precise_time_ns()
} else {
0
};
let istart = ccx.stats().n_llvm_insns.get();
StatRecorder {
ccx: ccx,
name: Some(name),
start: start,
istart: istart,
}
}
Expand All @@ -164,11 +155,8 @@ impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
fn drop(&mut self) {
if self.ccx.sess().trans_stats() {
let end = time::precise_time_ns();
let elapsed = ((end - self.start) / 1_000_000) as uint;
let iend = self.ccx.stats().n_llvm_insns.get();
self.ccx.stats().fn_stats.borrow_mut().push((self.name.take().unwrap(),
elapsed,
iend - self.istart));
self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
// Reset LLVM insn count to avoid compound costs.
Expand Down Expand Up @@ -3097,13 +3085,13 @@ pub fn trans_crate<'tcx>(analysis: CrateAnalysis<'tcx>)
println!("n_inlines: {}", stats.n_inlines.get());
println!("n_closures: {}", stats.n_closures.get());
println!("fn stats:");
stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
insns_b.cmp(&insns_a)
});
for tuple in stats.fn_stats.borrow().iter() {
match *tuple {
(ref name, ms, insns) => {
println!("{} insns, {} ms, {}", insns, ms, *name);
(ref name, insns) => {
println!("{} insns, {}", insns, *name);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/middle/trans/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ pub struct Stats {
pub n_closures: Cell<uint>,
pub n_llvm_insns: Cell<uint>,
pub llvm_insns: RefCell<FnvHashMap<String, uint>>,
// (ident, time-in-ms, llvm-instructions)
pub fn_stats: RefCell<Vec<(String, uint, uint)> >,
// (ident, llvm-instructions)
pub fn_stats: RefCell<Vec<(String, uint)> >,
}

/// The shared portion of a `CrateContext`. There is one `SharedCrateContext`
Expand Down
18 changes: 11 additions & 7 deletions src/librustc/util/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,30 @@

use std::cell::RefCell;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::fmt::Show;
use std::hash::{Hash, Hasher};
use std::time::Duration;

use syntax::ast;
use syntax::visit;
use syntax::visit::Visitor;

use time;

pub fn time<T, U>(do_it: bool, what: &str, u: U, f: |U| -> T) -> T {
local_data_key!(depth: uint);
if !do_it { return f(u); }

let old = depth.get().map(|d| *d).unwrap_or(0);
depth.replace(Some(old + 1));

let start = time::precise_time_s();
let rv = f(u);
let end = time::precise_time_s();
let mut u = Some(u);
let mut rv = None;
let dur = Duration::span(|| {
rv = Some(f(u.take().unwrap()))
});
let rv = rv.unwrap();

println!("{}time: {:3.3f} s\t{}", " ".repeat(old), end - start, what);
println!("{}time: {}.{:03} \t{}", " ".repeat(old),
dur.num_seconds(), dur.num_milliseconds(), what);
depth.replace(Some(old));

rv
Expand Down
4 changes: 0 additions & 4 deletions src/librustdoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ extern crate rustc;
extern crate serialize;
extern crate syntax;
extern crate "test" as testing;
extern crate time;
#[phase(plugin, link)] extern crate log;

use std::io;
Expand Down Expand Up @@ -238,7 +237,6 @@ pub fn main_args(args: &[String]) -> int {
};

info!("going to format");
let started = time::precise_time_ns();
match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
Some("html") | None => {
match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) {
Expand All @@ -257,8 +255,6 @@ pub fn main_args(args: &[String]) -> int {
return 1;
}
}
let ended = time::precise_time_ns();
info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);

return 0;
}
Expand Down
8 changes: 8 additions & 0 deletions src/libstd/time/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,14 @@ impl Duration {
Duration { secs: secs, nanos: nanos as i32 }
}

/// Runs a closure, returning the duration of time it took to run the
/// closure.
pub fn span(f: ||) -> Duration {
let before = super::precise_time_ns();
f();
Duration::nanoseconds((before - super::precise_time_ns()) as i64)
}

/// Returns the total number of whole weeks in the duration.
#[inline]
pub fn num_weeks(&self) -> i64 {
Expand Down
73 changes: 73 additions & 0 deletions src/libstd/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,79 @@

//! Temporal quantification.
use libc;

pub use self::duration::Duration;

pub mod duration;

/// Returns the current value of a high-resolution performance counter
/// in nanoseconds since an unspecified epoch.
// NB: this is intentionally not public, this is not ready to stabilize its api.
fn precise_time_ns() -> u64 {
return os_precise_time_ns();

#[cfg(windows)]
fn os_precise_time_ns() -> u64 {
let mut ticks_per_s = 0;
assert_eq!(unsafe {
libc::QueryPerformanceFrequency(&mut ticks_per_s)
}, 1);
let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
let mut ticks = 0;
assert_eq!(unsafe {
libc::QueryPerformanceCounter(&mut ticks)
}, 1);

return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
fn os_precise_time_ns() -> u64 {
use sync;

static mut TIMEBASE: libc::mach_timebase_info = libc::mach_timebase_info { numer: 0,
denom: 0 };
static ONCE: sync::Once = sync::ONCE_INIT;
unsafe {
ONCE.doit(|| {
imp::mach_timebase_info(&mut TIMEBASE);
});
let time = imp::mach_absolute_time();
time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
}
}

#[cfg(not(any(windows, target_os = "macos", target_os = "ios")))]
fn os_precise_time_ns() -> u64 {
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
unsafe {
imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
}
return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
}
}

#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios")))]
mod imp {
use libc::{c_int, timespec};

// Apparently android provides this in some other library?
#[cfg(not(target_os = "android"))]
#[link(name = "rt")]
extern {}

extern {
pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int;
}

}
#[cfg(any(target_os = "macos", target_os = "ios"))]
mod imp {
use libc::{c_int, mach_timebase_info};

extern {
pub fn mach_absolute_time() -> u64;
pub fn mach_timebase_info(info: *mut mach_timebase_info) -> c_int;
}
}
Loading

0 comments on commit 5745e41

Please sign in to comment.