sistema_progs

Programas para customizar o meu entorno de traballo nos meus equipos persoais
Log | Files | Refs

mach_gettime.c (1192B)


      1 #include "mach_gettime.h"
      2 #include <mach/mach_time.h>
      3 
      4 #define MT_NANO (+1.0E-9)
      5 #define MT_GIGA UINT64_C(1000000000)
      6 
      7 // TODO create a list of timers,
      8 static double mt_timebase = 0.0;
      9 static uint64_t mt_timestart = 0;
     10 
     11 int clock_gettime(clockid_t clk_id, struct timespec *tp)
     12 {
     13 	kern_return_t retval = KERN_SUCCESS;
     14 
     15 	if (clk_id == TIMER_ABSTIME) {
     16 		if (!mt_timestart) { // only one timer, initialized on the first call to the TIMER
     17 			mach_timebase_info_data_t tb;
     18 			mach_timebase_info(&tb);
     19 			mt_timebase = tb.numer;
     20 			mt_timebase /= tb.denom;
     21 			mt_timestart = mach_absolute_time();
     22 		}
     23 
     24 		double diff = (mach_absolute_time() - mt_timestart) * mt_timebase;
     25 		tp->tv_sec = diff * MT_NANO;
     26 		tp->tv_nsec = diff - (tp->tv_sec * MT_GIGA);
     27 	} else { // other clk_ids are mapped to the corresponding mach clock_service
     28 		clock_serv_t cclock;
     29 		mach_timespec_t mts;
     30 
     31 		host_get_clock_service(mach_host_self(), clk_id, &cclock);
     32 		retval = clock_get_time(cclock, &mts);
     33 		mach_port_deallocate(mach_task_self(), cclock);
     34 
     35 		tp->tv_sec = mts.tv_sec;
     36 		tp->tv_nsec = mts.tv_nsec;
     37 	}
     38 
     39 	return retval;
     40 }
     41 
     42 /*  Copyright (c) 2015-2018 Alf Watt - Open Source - https://opensource.org/licenses/MIT */