added 'videolib' snapshot
[k8-jellyphysics.git] / src / videolib / videolib_clock.c
blobc85e81feed58762b730950ec30e715297604ef03
1 /* coded by Ketmar // Vampire Avalon (psyc://ketmar.no-ip.org/~Ketmar)
2 * Understanding is not required. Only obedience.
4 * This program is free software. It comes without any warranty, to
5 * the extent permitted by applicable law. You can redistribute it
6 * and/or modify it under the terms of the Do What The Fuck You Want
7 * To Public License, Version 2, as published by Sam Hocevar. See
8 * http://www.wtfpl.net/txt/copying/ for more details.
9 */
10 #include "videolib.h"
11 #ifdef VIDEOLIB_ENABLE_CLOCK
13 #include <fcntl.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <time.h>
17 #include <unistd.h>
19 #include <sys/stat.h>
20 #include <sys/types.h>
23 /******************************************************************************/
24 static int k8clock_initialized = 0;
25 static struct timespec clk;
28 #ifndef CLOCK_MONOTONIC_RAW
29 # define K8CLOCK_CLOCK_TYPE CLOCK_MONOTONIC_RAW
30 #else
31 # define K8CLOCK_CLOCK_TYPE CLOCK_MONOTONIC
32 #endif
35 __attribute__((constructor)) static void _k8clock_ctor (void) {
36 struct timespec cres;
37 k8clock_initialized = -1;
38 if (clock_getres(K8CLOCK_CLOCK_TYPE, &cres) != 0) {
39 //fprintf(stderr, "ERROR: can't get clock resolution!\n");
40 return;
42 //fprintf(stderr, "CLOCK_MONOTONIC: %ld:%ld\n", cres.tv_sec, cres.tv_nsec);
43 if (cres.tv_sec > 0 || cres.tv_nsec > (long)1000000*10 /*10 ms*/) {
44 //fprintf(stderr, "ERROR: real-time clock resolution is too low!\n");
45 return;
47 if (clock_gettime(K8CLOCK_CLOCK_TYPE, &clk) != 0) {
48 //fprintf(stderr, "ERROR: real-time clock initialization failed!\n");
49 return;
51 k8clock_initialized = 1;
55 Uint64 vl_clock_milli (void) {
56 if (k8clock_initialized > 0) {
57 struct timespec ts;
58 if (clock_gettime(K8CLOCK_CLOCK_TYPE, &ts) != 0) {
59 //fprintf(stderr, "ERROR: can't get real-time clock value!\n");
60 return 0;
62 // ah, ignore nanoseconds in clk->stt here: we need only 'differential' time, and it can start with something weird
63 return ((Uint64)(ts.tv_sec-clk.tv_sec))*1000+ts.tv_nsec/1000000+1;
65 return 0;
69 Uint64 vl_clock_micro (void) {
70 if (k8clock_initialized > 0) {
71 struct timespec ts;
72 if (clock_gettime(K8CLOCK_CLOCK_TYPE, &ts) != 0) {
73 //fprintf(stderr, "ERROR: can't get real-time clock value!\n");
74 return 0;
76 // ah, ignore nanoseconds in clk->stt here: we need only 'differential' time, and it can start with something weird
77 return ((Uint64)(ts.tv_sec-clk.tv_sec))*1000000+ts.tv_nsec/1000+1;
79 return 0;
81 #endif