Skip to content

Commit

Permalink
[chore] Use elapsed() if possible when calculating durations (#750)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielsn authored Nov 20, 2024
1 parent 1b70e31 commit c6ad4ff
Show file tree
Hide file tree
Showing 17 changed files with 36 additions and 68 deletions.
2 changes: 1 addition & 1 deletion bin_tests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ macro_rules! timeit {
($op_name:literal, $op:block) => {{
let start = std::time::Instant::now();
let res = $op;
let delta = std::time::Instant::now().duration_since(start);
let delta = start.elapsed();
println!(
concat!($op_name, " took {} ms"),
delta.as_secs_f64() * 1000.0
Expand Down
2 changes: 1 addition & 1 deletion crashtracker/src/collector/crash_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ fn reap_child_non_blocking(pid: Pid, timeout_ms: u32) -> anyhow::Result<bool> {
loop {
match waitpid(pid, Some(WaitPidFlag::WNOHANG)) {
Ok(WaitStatus::StillAlive) => {
if Instant::now().duration_since(start_time) > timeout {
if start_time.elapsed() > timeout {
return Err(anyhow::anyhow!("Timeout waiting for child process to exit"));
}
}
Expand Down
4 changes: 2 additions & 2 deletions crashtracker/src/crash_info/telemetry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ impl TelemetryCrashUploader {

let tracer_time = match &crash_info.timestamp {
Some(ts) => ts.timestamp() as u64,
None => SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
None => SystemTime::UNIX_EPOCH
.elapsed()
.map(|d| d.as_secs())
.unwrap_or(0),
};
Expand Down
7 changes: 2 additions & 5 deletions data-pipeline/examples/send-traces-with-stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use data_pipeline::trace_exporter::{
use datadog_trace_protobuf::pb;
use std::{
collections::HashMap,
time::{Duration, SystemTime, UNIX_EPOCH},
time::{Duration, UNIX_EPOCH},
};

fn get_span(now: i64, trace_id: u64, span_id: u64) -> pb::Span {
Expand Down Expand Up @@ -44,10 +44,7 @@ fn main() {
.enable_stats(Duration::from_secs(10))
.build()
.unwrap();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos() as i64;
let now = UNIX_EPOCH.elapsed().unwrap().as_nanos() as i64;

let mut traces = Vec::new();
for trace_id in 1..=100 {
Expand Down
6 changes: 2 additions & 4 deletions data-pipeline/src/span_concentrator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@ mod aggregation;
/// Return a Duration between t and the unix epoch
/// If t is before the unix epoch return 0
fn system_time_to_unix_duration(t: SystemTime) -> Duration {
match t.duration_since(time::UNIX_EPOCH) {
Err(_) => Duration::from_nanos(0),
Ok(d) => d,
}
t.duration_since(time::UNIX_EPOCH)
.unwrap_or(Duration::from_nanos(0))
}

/// Align a timestamp on the start of a bucket
Expand Down
2 changes: 1 addition & 1 deletion ddtelemetry/examples/tm-metrics-worker-test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ macro_rules! timeit {
($op_name:literal, $op:block) => {{
let start = std::time::Instant::now();
let res = $op;
let delta = std::time::Instant::now().duration_since(start);
let delta = start.elapsed();
println!(
concat!($op_name, " took {} ms"),
delta.as_secs_f64() * 1000.0
Expand Down
5 changes: 1 addition & 4 deletions ddtelemetry/examples/tm-ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ fn build_request<'a>(
) -> data::Telemetry<'a> {
data::Telemetry {
api_version: data::ApiVersion::V1,
tracer_time: SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
tracer_time: SystemTime::UNIX_EPOCH.elapsed().map_or(0, |d| d.as_secs()),
runtime_id: "runtime_id",
seq_id: seq_id(),
application,
Expand Down
5 changes: 1 addition & 4 deletions ddtelemetry/examples/tm-send-sketch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ fn build_request<'a>(
) -> data::Telemetry<'a> {
data::Telemetry {
api_version: data::ApiVersion::V1,
tracer_time: SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
tracer_time: SystemTime::UNIX_EPOCH.elapsed().map_or(0, |d| d.as_secs()),
runtime_id: "runtime_id",
seq_id: seq_id(),
application,
Expand Down
2 changes: 1 addition & 1 deletion ddtelemetry/examples/tm-worker-test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ macro_rules! timeit {
($op_name:literal, $op:block) => {{
let start = std::time::Instant::now();
let res = $op;
let delta = std::time::Instant::now().duration_since(start);
let delta = start.elapsed();
println!(
concat!($op_name, " took {} ms"),
delta.as_secs_f64() * 1000.0
Expand Down
7 changes: 3 additions & 4 deletions ddtelemetry/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@ use serde::{Deserialize, Serialize};
use crate::data::{self, metrics};

fn unix_timestamp_now() -> u64 {
time::SystemTime::now()
.duration_since(time::SystemTime::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
time::SystemTime::UNIX_EPOCH
.elapsed()
.map_or(0, |d| d.as_secs())
}

#[derive(Debug)]
Expand Down
12 changes: 5 additions & 7 deletions ddtelemetry/src/worker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,8 @@ const CONTINUE: ControlFlow<()> = ControlFlow::Continue(());
const BREAK: ControlFlow<()> = ControlFlow::Break(());

fn time_now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.ok()
std::time::SystemTime::UNIX_EPOCH
.elapsed()
.unwrap_or_default()
.as_secs_f64()
}
Expand Down Expand Up @@ -631,10 +630,9 @@ impl TelemetryWorker {
let seq_id = self.next_seq_id();
let tel = Telemetry {
api_version: data::ApiVersion::V2,
tracer_time: time::SystemTime::now()
.duration_since(time::SystemTime::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
tracer_time: time::SystemTime::UNIX_EPOCH
.elapsed()
.map_or(0, |d| d.as_secs()),
runtime_id: &self.runtime_id,
seq_id,
host: &self.data.host,
Expand Down
12 changes: 6 additions & 6 deletions dogstatsd/src/aggregator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ impl Aggregator {

#[must_use]
pub fn distributions_to_protobuf(&self) -> SketchPayload {
let now = time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
let now = time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
Expand All @@ -138,8 +138,8 @@ impl Aggregator {

#[must_use]
pub fn consume_distributions(&mut self) -> Vec<SketchPayload> {
let now = time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
let now = time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
Expand Down Expand Up @@ -286,8 +286,8 @@ fn build_metric(entry: &Metric, mut base_tag_vec: SortedTags) -> Option<MetricTo
let point = datadog::Point {
value: entry.value.get_value()?,
// TODO(astuyve) allow user to specify timestamp
timestamp: time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
timestamp: time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs(),
};
Expand Down
4 changes: 1 addition & 3 deletions sidecar/src/service/blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,9 +532,7 @@ pub fn ping(transport: &mut SidecarTransport) -> io::Result<Duration> {
let start = Instant::now();
transport.call(SidecarInterfaceRequest::Ping {})?;

Ok(Instant::now()
.checked_duration_since(start)
.unwrap_or_default())
Ok(start.elapsed())
}

#[cfg(test)]
Expand Down
8 changes: 2 additions & 6 deletions trace-mini-agent/src/stats_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use std::time::UNIX_EPOCH;

use async_trait::async_trait;
use hyper::{http, Body, Request, Response, StatusCode};
Expand Down Expand Up @@ -63,11 +63,7 @@ impl StatsProcessor for ServerlessStatsProcessor {
};

if !stats.stats.is_empty() {
let start = SystemTime::now();
let timestamp = start
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let timestamp = UNIX_EPOCH.elapsed().unwrap_or_default().as_nanos();
stats.stats[0].start = timestamp as u64;
}

Expand Down
11 changes: 2 additions & 9 deletions trace-mini-agent/src/trace_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,7 @@ impl TraceProcessor for ServerlessTraceProcessor {
mod tests {
use datadog_trace_obfuscation::obfuscation_config::ObfuscationConfig;
use hyper::Request;
use std::{
collections::HashMap,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use std::{collections::HashMap, sync::Arc, time::UNIX_EPOCH};
use tokio::sync::mpsc::{self, Receiver, Sender};

use crate::{
Expand All @@ -142,10 +138,7 @@ mod tests {
use ddcommon::Endpoint;

fn get_current_timestamp_nanos() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos() as i64
UNIX_EPOCH.elapsed().unwrap().as_nanos() as i64
}

fn create_test_config() -> Config {
Expand Down
10 changes: 4 additions & 6 deletions trace-normalization/src/normalize_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,10 @@ pub fn normalize_span_start_duration(start: &mut i64, duration: &mut i64) {
}

if *start < YEAR_2000_NANOSEC_TS {
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map_or_else(
|e| -(e.duration().as_nanos() as i64),
|t| t.as_nanos() as i64,
);
let now = SystemTime::UNIX_EPOCH.elapsed().map_or_else(
|e| -(e.duration().as_nanos() as i64),
|t| t.as_nanos() as i64,
);
*start = now - *duration;
if *start < 0 {
*start = now;
Expand Down
5 changes: 1 addition & 4 deletions trace-normalization/src/normalizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,7 @@ mod tests {
}

fn get_current_time() -> i64 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_nanos() as i64
SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos() as i64
}

#[test]
Expand Down

0 comments on commit c6ad4ff

Please sign in to comment.