From 1341df0682c408b4b4a1af22acb5fc1b9cbc6705 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciro=20Santilli=20=E5=85=AD=E5=9B=9B=E4=BA=8B=E4=BB=B6=20?= =?UTF-8?q?=E6=B3=95=E8=BD=AE=E5=8A=9F?= Date: Tue, 2 Jun 2020 01:00:00 +0000 Subject: [PATCH] timespect_get: move from cpp-cheat --- README.adoc | 4 ++++ userland/c/timespec_get.c | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 userland/c/timespec_get.c diff --git a/README.adoc b/README.adoc index fed840e..edd841e 100644 --- a/README.adoc +++ b/README.adoc @@ -17107,6 +17107,10 @@ Good sanity check for user mode: <> *** File IO **** link:userland/c/file_write_read.c[] **** link:userland/linux/open_o_tmpfile.c[]: https://stackoverflow.com/questions/4508998/what-is-an-anonymous-inode-in-linux/44388030#44388030 +** `time.h` +*** link:userland/c/timespec_get.c[] `timespec_get` is a C11 for `clock_gettime` http://stackoverflow.com/questions/361363/how-to-measure-time-in-milliseconds-using-ansi-c/36095407#36095407 ++ +Vs `clock()`: http://stackoverflow.com/questions/12392278/measure-time-in-linux-getrusage-vs-clock-gettime-vs-clock-vs-gettimeofday * Fun ** link:userland/c/loop.c[] diff --git a/userland/c/timespec_get.c b/userland/c/timespec_get.c new file mode 100644 index 0000000..27f281b --- /dev/null +++ b/userland/c/timespec_get.c @@ -0,0 +1,34 @@ +/* https://cirosantilli.com/linux-kernel-module-cheat#c + */ + +#include +#include +#include + +/* We use double because time_t can be either floating point or integer. + * POSIX guarantees that it is an integer, we could use uintmax_t then. */ +static long double get_nanos(void) { + struct timespec ts; + timespec_get(&ts, TIME_UTC); + return ts.tv_sec * 1e9 + ts.tv_nsec; +} + +int main(int argc, char **argv) { + long double start; + unsigned long long int i, niters; + + if (argc > 1) { + niters = strtoull(argv[1], NULL, 0); + } else { + niters = 3; + } + i = 0; + start = get_nanos(); + while (1) { + printf("%Lf\n", get_nanos() - start); + i++; + if (i == niters) + break; + } + return EXIT_SUCCESS; +}