Skip to content

Commit

Permalink
time: Deprecate the library in the distribution
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 #18855, some of the conversions in the `src/test/bench` area may have been a
little nicer with that implemented
  • Loading branch information
alexcrichton committed Nov 12, 2014
1 parent e4ead7b commit fcd05ed
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
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
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
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
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
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
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
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
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);

This comment has been minimized.

Copy link
@pnkfelix

pnkfelix Feb 25, 2015

Member

fyi @alexcrichton i think this multiply is overflowing. In all branches; its just that the arithmetic-overflow branch is now catching it happening.

Obviously the multiply does not live here anymore; it has AFAICT been migrated to std::sys::windows::time

The only evidence I have currently of the overflow is here: try build log
(scroll to the bottom, you'll see at the end the following message:)

thread 'rustc' panicked at 'arithmetic operation overflowed',
C:\bot\slave\try-win-32\build\src\libstd\sys\windows\time.rs:27

This comment has been minimized.

Copy link
@pnkfelix

pnkfelix Feb 25, 2015

Member

BTW I mention this only because I thought it was an interesting instance of overflow cropping up. I am using the following reformulation to avoid the overflow (hopefully): pnkfelix@b6d2ccb

But I would be curious to know your thoughts as to what possible fallout there is from the overflow here. I have not yet attempted to observe how much it may or may not be messing up the result of fn ns().

This comment has been minimized.

Copy link
@huonw

huonw Feb 25, 2015

Member

cc #22788

This comment has been minimized.

Copy link
@alexcrichton

alexcrichton Feb 25, 2015

Author Member

Oh dear that's not good! Looks like @vadimcn is on the case though with the PR @huonw mentioned

This comment has been minimized.

Copy link
@pnkfelix

pnkfelix Feb 25, 2015

Member

It looks like @vadimcn's approach is just to divide before doing the multiply; this certainly avoids the overflow, but also throws away information.

I believe my technique avoids losing the least significant digits in a portable way.

This comment has been minimized.

Copy link
@pnkfelix

pnkfelix Feb 25, 2015

Member

(I apologize, the previous comment was written before i had had my first cup of coffee. :( )

}

#[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;
}
}

5 comments on commit fcd05ed

@bors
Copy link
Contributor

@bors bors commented on fcd05ed Nov 12, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

saw approval from jakub
at alexcrichton@fcd05ed

@bors
Copy link
Contributor

@bors bors commented on fcd05ed Nov 12, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging alexcrichton/rust/remove-time = fcd05ed into auto

@bors
Copy link
Contributor

@bors bors commented on fcd05ed Nov 12, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alexcrichton/rust/remove-time = fcd05ed merged ok, testing candidate = 5745e41

@bors
Copy link
Contributor

@bors bors commented on fcd05ed Nov 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on fcd05ed Nov 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding master to auto = 5745e41

Please sign in to comment.