diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6936990 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +**/*.rs.bk +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4559e11 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "howlong" +version = "0.1.0" +authors = ["Cheng XU "] +edition = "2018" +build = "build.rs" +license = "MIT OR Apache-2.0" +repository = "https://github.com/xu-cheng/howlong" +readme = "README.md" + +[dependencies] +thiserror = "1.0" +cfg-if = "0.1" + +[target.'cfg(unix)'.dependencies] +errno = "0.2" +libc = "0.2" + +[target.'cfg(windows)'.dependencies] +winapi = "0.3" + +[target.'cfg(unix)'.build-dependencies] +cc = "1.0" + +[target.'cfg(any(target_os = "macos", target_os = "ios"))'.build-dependencies] +bindgen = "0.52" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..2c282a3 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Cheng XU + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0e38633 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# howlong diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..c16a1d1 --- /dev/null +++ b/build.rs @@ -0,0 +1,66 @@ +#[cfg(any(target_os = "macos", target_os = "ios"))] +extern crate bindgen; +#[cfg(unix)] +extern crate cc; + +#[cfg(unix)] +fn is_defined(m: &'static str) -> bool { + let file = format!("{}/test_{}.c", std::env::var("OUT_DIR").unwrap(), m); + std::fs::write( + &file, + format!( + r#" + #include + + #ifdef {} + MACRO_IS_DEFINED + #endif + "#, + m + ), + ) + .unwrap(); + let check = cc::Build::new().file(&file).expand(); + let check = String::from_utf8(check).unwrap(); + check.contains("MACRO_IS_DEFINED") +} + +#[cfg(not(unix))] +fn is_defined(_m: &'static str) -> bool { + false +} + +#[cfg(any(target_os = "macos", target_os = "ios"))] +fn gen_darwin_binding() { + use std::path::PathBuf; + + println!("cargo:rerun-if-changed=src/clock/darwin_wrapper.h"); + + let bindings = bindgen::Builder::default() + .header("src/clock/darwin_wrapper.h") + .parse_callbacks(Box::new(bindgen::CargoCallbacks)) + .layout_tests(false) + .generate() + .expect("Unable to generate bindings"); + let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap()); + bindings + .write_to_file(out_path.join("darwin_bindings.rs")) + .expect("Couldn't write bindings!"); +} + +fn main() { + let have_steady_clock = if cfg!(any(target_os = "macos", target_os = "ios", windows)) { + true + } else { + is_defined("CLOCK_MONOTONIC") + }; + if have_steady_clock { + println!("cargo:rustc-cfg=have_steady_clock"); + } + if cfg!(unix) && is_defined("CLOCK_THREAD_CPUTIME_ID") { + println!("cargo:rustc-cfg=have_clock_thread_cputime_id"); + } + + #[cfg(any(target_os = "macos", target_os = "ios"))] + gen_darwin_binding(); +} diff --git a/src/clock/darwin.rs b/src/clock/darwin.rs new file mode 100644 index 0000000..b3c3859 --- /dev/null +++ b/src/clock/darwin.rs @@ -0,0 +1,92 @@ +// Ref: https://github.com/boostorg/chrono/tree/develop/include/boost/chrono/detail/inlined/mac + +extern crate libc; + +use crate::{Duration, Error, Result, TimePoint}; +use std::mem; + +#[allow(dead_code)] +#[path = "./posix.rs"] +mod posix; + +mod mach { + #![allow(clippy::all)] + #![allow(dead_code)] + #![allow(non_camel_case_types)] + #![allow(non_snake_case)] + #![allow(non_upper_case_globals)] + #![allow(safe_packed_borrows)] + include!(concat!(env!("OUT_DIR"), "/darwin_bindings.rs")); +} + +/// A system clock. +// `gettimeofday` is the most precise "system time" available on macOS. +pub struct SystemClock; + +impl SystemClock { + pub fn now() -> Result { + let mut tv = libc::timeval { + tv_sec: 0, + tv_usec: 0, + }; + let ret = unsafe { libc::gettimeofday(&mut tv, core::ptr::null_mut()) }; + if ret != 0 { + return Err(Error::SystemError("gettimeofday", posix::errno())); + } + let d = Duration::from_secs(tv.tv_sec as u64) + Duration::from_micros(tv.tv_usec as u64); + Ok(TimePoint(d)) + } +} + +/// A steady clock. +// On macOS, it is based on `mach_absolute_time`. +// `mach_absolute_time() * MachInfo.numer / MachInfo.denom` is the number of +// nanoseconds since the computer booted up. +pub struct SteadyClock; + +impl SteadyClock { + pub fn now() -> Result { + let mut info: mach::mach_timebase_info_data_t = unsafe { mem::zeroed() }; + let ret = unsafe { mach::mach_timebase_info(&mut info) }; + if ret != 0 { + return Err(Error::SystemError("mach_timebase_info", ret)); + } + let absolute_time = unsafe { mach::mach_absolute_time() }; + let d = if info.numer == info.denom { + Duration::from_nanos(absolute_time) + } else { + let factor = (info.numer as f64) / (info.denom as f64); + Duration::from_nanos(absolute_time * (factor as u64)) + }; + Ok(TimePoint(d)) + } +} + +pub use posix::{ProcessCPUClock, ProcessRealCPUClock, ProcessSystemCPUClock, ProcessUserCPUClock}; + +/// A clock to report the real thread wall-clock. +pub struct ThreadClock; + +impl ThreadClock { + pub fn now() -> Result { + let port = unsafe { mach::pthread_mach_thread_np(mach::pthread_self()) }; + let mut info: mach::thread_basic_info_data_t = unsafe { mem::zeroed() }; + let mut count: mach::mach_msg_type_number_t = mach::__THREAD_BASIC_INFO_COUNT; + let ret = unsafe { + mach::thread_info( + port, + mach::THREAD_BASIC_INFO, + &mut info as *mut mach::thread_basic_info as *mut i32, + &mut count, + ) + }; + if ret != 0 { + return Err(Error::SystemError("thread_info", ret)); + } + let user = Duration::from_secs(info.user_time.seconds as u64) + + Duration::from_micros(info.user_time.microseconds as u64); + let system = Duration::from_secs(info.system_time.seconds as u64) + + Duration::from_micros(info.system_time.microseconds as u64); + Ok(TimePoint(user + system)) + } +} diff --git a/src/clock/darwin_wrapper.h b/src/clock/darwin_wrapper.h new file mode 100644 index 0000000..06f0070 --- /dev/null +++ b/src/clock/darwin_wrapper.h @@ -0,0 +1,5 @@ +#include +#include +#include + +const mach_msg_type_number_t __THREAD_BASIC_INFO_COUNT = THREAD_BASIC_INFO_COUNT; diff --git a/src/clock/mod.rs b/src/clock/mod.rs new file mode 100644 index 0000000..02ea962 --- /dev/null +++ b/src/clock/mod.rs @@ -0,0 +1,63 @@ +//! Measure the current time using different clocks. +//! +//! The following list of clocks are implemented. +//! * [`SystemClock`]: It provides access to the current wall-clock time from the system-wide +//! real-time clock. +//! * [`SteadyClock`]: It provides access to system-wide steady clock. There is no fixed +//! relationship between values returned by `SteadyClock::now()` and wall-clock time +//! * [`HighResolutionClock`]: Default to `SteadyClock` if available, otherwise fallback to +//! `SystemClock`. +//! * [`ProcessRealCPUClock`]: It provides access to the real process wall-clock steady clock, +//! i.e. the real CPU-time clock of the calling process. +//! * [`ProcessUserCPUClock`]: It provides access to the user CPU-time steady clock of the +//! calling process. +//! * [`ProcessSystemCPUClock`]: It provides access to the system CPU-time steady clock of +//! the calling process. +//! * [`ProcessCPUClock`]: It provides access to real, user-CPU, and system-CPU clocks at +//! the same time. +//! * [`ThreadClock`]: It provides access to the real thread wall-clock, i.e. the real CPU-time +//! clock of the calling thread. +//! +//! # Implementations +//! +//! The Implementations of the clocks are based on +//! [`boost-chrono` library](http://boost.org/libs/chrono) +//! The following table listes the underlying APIs for different clocks. +//! +//! | Clock | Posix | Darwin | Windows | +//! |-------|-------|--------|---------| +//! | [`SystemClock`] | `clock_gettime(CLOCK_REALTIME)` | `gettimeofday` | `GetSystemTimeAsFileTime` | +//! | [`SteadyClock`] | `clock_gettime(CLOCK_MONOTONIC)` | `mach_timebase_info`, `mach_absolute_time` | `QueryPerformanceCounter`, `QueryPerformanceFrequency` | +//! | [`ProcessRealCPUClock`] | `times` | `times` | `GetProcessTimes` | +//! | [`ProcessUserCPUClock`] | `times` | `times` | `GetProcessTimes` | +//! | [`ProcessSystemCPUClock`] | `times` | `times` | `GetProcessTimes` | +//! | [`ProcessCPUClock`] | `times` | `times` | `GetProcessTimes` | +//! | [`ThreadClock`] | `clock_gettime(pthread_getcpuclockid)` | `thread_info` | `GetThreadTimes` | + +cfg_if::cfg_if! { + if #[cfg(any(target_os = "macos", target_os = "ios"))] { + // Darwin + mod darwin; + pub use darwin::*; + } else if #[cfg(windows)] { + // Windows + mod win; + pub use win::*; + } else if #[cfg(unix)] { + // Posix + mod posix; + pub use posix::*; + } else { + compile_error!("unsupported platform."); + } +} + +cfg_if::cfg_if! { + if #[cfg(have_steady_clock)] { + /// A high resolution clock. + pub type HighResolutionClock = SteadyClock; + } else { + /// A high resolution clock. + pub type HighResolutionClock = SystemClock; + } +} diff --git a/src/clock/posix.rs b/src/clock/posix.rs new file mode 100644 index 0000000..411a086 --- /dev/null +++ b/src/clock/posix.rs @@ -0,0 +1,169 @@ +// Ref: https://github.com/boostorg/chrono/tree/develop/include/boost/chrono/detail/inlined/posix + +extern crate errno; +extern crate libc; + +use crate::{Duration, Error, ProcessTimePoint, Result, TimePoint}; + +pub(crate) fn errno() -> i32 { + errno::errno().into() +} + +/// A system clock. +pub struct SystemClock; + +impl SystemClock { + pub fn now() -> Result { + let mut ts = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + let ret = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts) }; + if ret != 0 { + return Err(Error::SystemError("clock_gettime", errno())); + } + let d = Duration::from_secs(ts.tv_sec as u64) + Duration::from_nanos(ts.tv_nsec as u64); + Ok(TimePoint(d)) + } +} + +/// A steady clock. +#[cfg(have_steady_clock)] +pub struct SteadyClock; + +#[cfg(have_steady_clock)] +impl SteadyClock { + pub fn now() -> Result { + let mut ts = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + let ret = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) }; + if ret != 0 { + return Err(Error::SystemError("clock_gettime", errno())); + } + let d = Duration::from_secs(ts.tv_sec as u64) + Duration::from_nanos(ts.tv_nsec as u64); + Ok(TimePoint(d)) + } +} + +fn tick_factor() -> Result { + let factor = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; + if factor <= 0 { + return Err(Error::SystemError("sysconf(_SC_CLK_TCK)", errno())); + } + if factor > 1_000_000_000 { + return Err(Error::ClkFreqTooHigh); + } + Ok((1_000_000_000 / factor) as u64) +} + +#[inline(always)] +fn times() -> Result<(libc::clock_t, libc::tms)> { + let mut tm = libc::tms { + tms_utime: 0, + tms_stime: 0, + tms_cutime: 0, + tms_cstime: 0, + }; + let ret = unsafe { libc::times(&mut tm) }; + if ret == -1i64 as libc::clock_t { + return Err(Error::SystemError("times", errno())); + } + Ok((ret, tm)) +} + +/// A clock to report the real process wall-clock. +pub struct ProcessRealCPUClock; + +impl ProcessRealCPUClock { + pub fn now() -> Result { + let (c, _) = times()?; + let factor = tick_factor()?; + let d = Duration::from_nanos((c as u64) * factor); + Ok(TimePoint(d)) + } +} + +/// A clock to report the user cpu-clock. +pub struct ProcessUserCPUClock; + +impl ProcessUserCPUClock { + pub fn now() -> Result { + let (_, tm) = times()?; + let factor = tick_factor()?; + let d = Duration::from_nanos(((tm.tms_utime + tm.tms_cutime) as u64) * factor); + Ok(TimePoint(d)) + } +} + +/// A clock to report the system cpu-clock. +pub struct ProcessSystemCPUClock; + +impl ProcessSystemCPUClock { + pub fn now() -> Result { + let (_, tm) = times()?; + let factor = tick_factor()?; + let d = Duration::from_nanos(((tm.tms_stime + tm.tms_cstime) as u64) * factor); + Ok(TimePoint(d)) + } +} + +/// A clock to report real, user-CPU, and system-CPU clocks. +pub struct ProcessCPUClock; + +impl ProcessCPUClock { + pub fn now() -> Result { + let (c, tm) = times()?; + let factor = tick_factor()?; + Ok(ProcessTimePoint { + real: Duration::from_nanos((c as u64) * factor), + user: Duration::from_nanos(((tm.tms_utime + tm.tms_cutime) as u64) * factor), + system: Duration::from_nanos(((tm.tms_stime + tm.tms_cstime) as u64) * factor), + }) + } +} + +/// A clock to report the real thread wall-clock. +pub struct ThreadClock; + +#[cfg(not(have_clock_thread_cputime_id))] +extern "C" { + fn pthread_getcpuclockid( + thread_id: libc::pthread_t, + clock_id: *mut libc::clockid_t, + ) -> libc::c_int; +} + +impl ThreadClock { + #[cfg(have_clock_thread_cputime_id)] + #[inline(always)] + fn get_thread_clock_id() -> Result { + Ok(libc::CLOCK_THREAD_CPUTIME_ID) + } + + #[cfg(not(have_clock_thread_cputime_id))] + #[inline(always)] + fn get_thread_clock_id() -> Result { + let mut clock_id: libc::clockid_t = 0; + let ret = unsafe { pthread_getcpuclockid(libc::pthread_self(), &mut clock_id) }; + if ret != 0 { + return Err(Error::SystemError("pthread_getcpuclockid", errno())); + } + Ok(clock_id) + } + + pub fn now() -> Result { + let mut ts = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + let clock_id = Self::get_thread_clock_id()?; + let ret = unsafe { libc::clock_gettime(clock_id, &mut ts) }; + if ret != 0 { + return Err(Error::SystemError("clock_gettime", errno())); + } + let d = Duration::from_secs(ts.tv_sec as u64) + Duration::from_nanos(ts.tv_nsec as u64); + Ok(TimePoint(d)) + } +} diff --git a/src/clock/win.rs b/src/clock/win.rs new file mode 100644 index 0000000..986772f --- /dev/null +++ b/src/clock/win.rs @@ -0,0 +1,77 @@ +// Ref: https://github.com/boostorg/chrono/tree/develop/include/boost/chrono/detail/inlined/win + +extern crate winapi; + +use winapi::shared::minwindef::FILETIME; +use winapi::um::{ + errhandlingapi::GetLastError, + processthreadsapi::{GetCurrentProcess, GetCurrentThread, GetProcessTimes, GetThreadTimes}, + profileapi::{QueryPerformanceCounter, QueryPerformanceFrequency}, + sysinfoapi::GetSystemTimeAsFileTime, + winnt::LARGE_INTEGER, +}; + +use crate::{Duration, Error, ProcessTimePoint, Result, TimePoint}; + +/// A system clock. +pub struct SystemClock; + +impl SystemClock { + pub fn now() -> Result { + unimplemented!(); + } +} + +/// A steady clock. +pub struct SteadyClock; + +impl SteadyClock { + pub fn now() -> Result { + unimplemented!(); + } +} + +/// A clock to report the real process wall-clock. +pub struct ProcessRealCPUClock; + +impl ProcessRealCPUClock { + pub fn now() -> Result { + unimplemented!(); + } +} + +/// A clock to report the user cpu-clock. +pub struct ProcessUserCPUClock; + +impl ProcessUserCPUClock { + pub fn now() -> Result { + unimplemented!(); + } +} + +/// A clock to report the system cpu-clock. +pub struct ProcessSystemCPUClock; + +impl ProcessSystemCPUClock { + pub fn now() -> Result { + unimplemented!(); + } +} + +/// A clock to report real, user-CPU, and system-CPU clocks. +pub struct ProcessCPUClock; + +impl ProcessCPUClock { + pub fn now() -> Result { + unimplemented!(); + } +} + +/// A clock to report the real thread wall-clock. +pub struct ThreadClock; + +impl ThreadClock { + pub fn now() -> Result { + unimplemented!(); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..85776ce --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,8 @@ +mod types; +pub use types::*; + +pub mod clock; +pub use clock::*; + +pub mod timer; +pub use timer::*; diff --git a/src/timer.rs b/src/timer.rs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/timer.rs @@ -0,0 +1 @@ + diff --git a/src/types.rs b/src/types.rs new file mode 100644 index 0000000..1e79e16 --- /dev/null +++ b/src/types.rs @@ -0,0 +1,99 @@ +extern crate thiserror; + +use core::ops::{Add, AddAssign, Sub, SubAssign}; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + /// Error during the system call. + #[error("failed to call `{0}` [errno: {1}]")] + SystemError(&'static str, i32), + /// Error if `sysconf(_SC_CLK_TCK)` returns a too large value + #[error("the clock frequence is too high.")] + ClkFreqTooHigh, +} + +pub type Result = core::result::Result; + +pub use core::time::Duration; + +/// A point in time. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct TimePoint(pub(crate) Duration); + +impl Sub for TimePoint { + type Output = Duration; + + #[inline(always)] + fn sub(self, other: Self) -> Self::Output { + self.0 - other.0 + } +} + +/// Like [`TimePoint`] but captures real, user-CPU, and system-CPU process times. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ProcessTimePoint { + pub(crate) real: Duration, + pub(crate) user: Duration, + pub(crate) system: Duration, +} + +impl Sub for ProcessTimePoint { + type Output = ProcessDuration; + + #[inline(always)] + fn sub(self, other: Self) -> Self::Output { + ProcessDuration { + real: self.real - other.real, + user: self.user - other.user, + system: self.system - other.system, + } + } +} + +/// Like [`Duration`] but captures real, user-CPU, and system-CPU process times. +#[derive(Clone, Copy, Debug, Default)] +pub struct ProcessDuration { + pub real: Duration, + pub user: Duration, + pub system: Duration, +} + +impl Add for ProcessDuration { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: Self) -> Self::Output { + ProcessDuration { + real: self.real + rhs.real, + user: self.user + rhs.user, + system: self.system + rhs.system, + } + } +} + +impl AddAssign for ProcessDuration { + #[inline(always)] + fn add_assign(&mut self, rhs: Self) { + *self = *self + rhs; + } +} + +impl Sub for ProcessDuration { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Self) -> Self::Output { + ProcessDuration { + real: self.real - rhs.real, + user: self.user - rhs.user, + system: self.system - rhs.system, + } + } +} + +impl SubAssign for ProcessDuration { + #[inline(always)] + fn sub_assign(&mut self, rhs: Self) { + *self = *self - rhs; + } +} diff --git a/tests/clock.rs b/tests/clock.rs new file mode 100644 index 0000000..57fabeb --- /dev/null +++ b/tests/clock.rs @@ -0,0 +1,71 @@ +extern crate howlong; + +use howlong::{clock::*, Duration}; +use std::thread; + +macro_rules! test_clock { + ($name: ident, $clock: ty) => { + #[test] + fn $name() { + let ten_millis = Duration::from_millis(10); + let start = <$clock>::now().unwrap(); + thread::sleep(ten_millis); + let elapsed = <$clock>::now().unwrap() - start; + assert!(elapsed >= ten_millis); + } + }; +} + +test_clock!(test_system_clock, SystemClock); +#[cfg(have_steady_clock)] +test_clock!(test_steady_clock, SteadyClock); +test_clock!(test_high_resolution_clock, HighResolutionClock); +test_clock!(test_process_real_cpu_clock, ProcessRealCPUClock); + +fn computation_task() { + let _ = (0..1_000_000).fold(0, |old, new| old ^ new); +} + +#[test] +fn test_process_user_cpu_clock() { + let start = ProcessUserCPUClock::now().unwrap(); + computation_task(); + let elapsed = ProcessUserCPUClock::now().unwrap() - start; + assert!(elapsed > Duration::from_nanos(0)); +} + +#[test] +fn test_process_system_cpu_clock() { + let start = ProcessSystemCPUClock::now().unwrap(); + let elapsed = ProcessSystemCPUClock::now().unwrap() - start; + assert!(elapsed < Duration::from_nanos(10)); +} + +#[test] +fn test_process_cpu_clock() { + let start = ProcessCPUClock::now().unwrap(); + (0..4) + .map(|_| thread::spawn(|| computation_task())) + .for_each(|t| { + let _ = t.join(); + }); + let elapsed = ProcessCPUClock::now().unwrap() - start; + assert!(elapsed.real > Duration::from_nanos(0)); + assert!(elapsed.user > Duration::from_nanos(0)); + assert!(elapsed.user + elapsed.system >= elapsed.real); +} + +#[test] +fn test_thread_clock() { + let start_outter = ThreadClock::now().unwrap(); + let elapsed_inner = thread::spawn(|| { + let start_inner = ThreadClock::now().unwrap(); + computation_task(); + ThreadClock::now().unwrap() - start_inner + }) + .join() + .unwrap(); + let elapsed_outter = ThreadClock::now().unwrap() - start_outter; + assert!(elapsed_inner > Duration::from_nanos(0)); + assert!(elapsed_inner > elapsed_outter); +}