timespect_get: move from cpp-cheat

This commit is contained in:
Ciro Santilli 六四事件 法轮功
2020-06-02 01:00:00 +00:00
parent 7411ad1354
commit 1341df0682
2 changed files with 38 additions and 0 deletions

View File

@@ -17107,6 +17107,10 @@ Good sanity check for user mode: <<qemu-user-mode-getting-started>>
*** File IO *** File IO
**** link:userland/c/file_write_read.c[] **** 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 **** 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 * Fun
** link:userland/c/loop.c[] ** link:userland/c/loop.c[]

34
userland/c/timespec_get.c Normal file
View File

@@ -0,0 +1,34 @@
/* https://cirosantilli.com/linux-kernel-module-cheat#c
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* 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;
}