Measuring Elapsed Time in C and Rust
C: <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
enum { v_size = 100000000 };
void long_function() {
double* v = malloc(v_size * sizeof(double));
if (!v) {
fprintf(stderr, "Memory allocation failed!\n");
exit(1);
}
// initializing array to all 55's
for (int i = 0; i < v_size; i += 1) {
v[i] = 55;
}
// performing the transformation
for (int i = 0; i < v_size; i += 1) {
v[i] += 1;
}
free(v);
}
int main() {
// current time measured in seconds relative to an epoch
time_t start_calendar = time(0);
// raw processor clock time since the program started
clock_t start_clock = clock();
// new in C11, returns calendar time in seconds and nanoseconds based on a
// given time base
struct timespec start_timespec = {0};
timespec_get(&start_timespec, TIME_UTC); // this function has an error return
// type, ignoring it for brevity
long_function();
time_t end_calendar = time(0);
clock_t end_clock = clock();
struct timespec end_timespec = {0};
timespec_get(&end_timespec, TIME_UTC);
// computes the difference between two time_t calendar time in seconds
double calendar_diff = difftime(end_calendar, start_calendar);
// difference between two clock_t using CLOCKS_PER_SEC
double clock_diff = 1.0 * (end_clock - start_clock) / CLOCKS_PER_SEC;
// difference between two timespecs
double timespec_sec_diff =
difftime(end_timespec.tv_sec, start_timespec.tv_sec);
long timespec_nanosec_diff = end_timespec.tv_nsec - start_timespec.tv_nsec;
printf("calendar_diff: %lf\nclock_diff: %lf\ntimespec_sec_diff: "
"%lf\ntimespec_nanosec_diff: %ld",
calendar_diff, clock_diff, timespec_sec_diff, timespec_nanosec_diff);
}
Rust: std::time
use std::time::{Duration, Instant, SystemTime};
// Function which presumably takes a while to execute
fn long_function() {
let mut v = vec![55; 100000000];
v.iter_mut().for_each(|x| *x += 1);
}
fn main() {
// A system clock which uses your operating systems current time
// This can go backwards!
let start_system = SystemTime::now();
// A monotonic non-decreasing clock, i.e. a clock that should always increase
// by the same amount, and never go backwards.
let start_instant = Instant::now();
long_function();
// Because the system clock is susceptible to drift and could
// go backwards, this operation returns a result.
let duration_system = start_system.elapsed().unwrap();
// there is no possibility of this occurring with durations from Instants
let duration_instant = start_instant.elapsed();
println!(
"Time elapsed in long function: \nSystemTime: {:?}\nInstant: {:?}",
// defaults to milliseconds if an as_period() is not used
duration_system,
// converts to floating point seconds, see the docs for other
// possible as_*() methods
duration_instant.as_secs_f32()
);
}
Thanks for reading! Read other posts?