3 /* xbt_os_time.c -- portable interface to time-related functions */
5 /* Copyright (c) 2004-2008 The SimGrid team. All rights reserved. */
7 /* This program is free software; you can redistribute it and/or modify it
8 * under the terms of the license (GNU LGPL) which comes with this package. */
10 #include "xbt/sysdep.h"
11 #include "xbt/xbt_os_time.h" /* this module */
14 #include <math.h> /* floor */
18 #include <sys/timeb.h>
21 double xbt_os_time(void) {
22 #ifdef HAVE_GETTIMEOFDAY
24 gettimeofday(&tv, NULL);
27 # if defined(WIN32_WCE) || (_WIN32_WINNT < 0x0400)
33 tv.tv_usec = tm.millitm * 1000;
39 GetSystemTimeAsFileTime (&ft);
40 tm = (unsigned __int64)ft.dwHighDateTime << 32;
41 tm |= ft.dwLowDateTime;
43 tm -= 11644473600000000ULL;
45 tv.tv_sec = (long) (tm / 1000000L);
46 tv.tv_usec = (long) (tm % 1000000L);
47 # endif /* windows version checker */
49 #else /* not windows, no gettimeofday => poor resolution */
50 return (double)(time(NULL));
51 #endif /* HAVE_GETTIMEOFDAY? */
53 return (double)(tv.tv_sec + tv.tv_usec / 1000000.0);
56 void xbt_os_sleep(double sec) {
59 (void)usleep( (sec - floor(sec)) * 1000000);
62 Sleep((floor(sec) * 1000) +((sec - floor(sec)) * 1000));
64 #else /* don't have usleep. Use select to sleep less than one second */
65 struct timeval timeout;
68 timeout.tv_sec = (unsigned long)(sec);
69 timeout.tv_usec = (sec - floor(sec)) * 1000000;
71 select(0, NULL, NULL, NULL, &timeout);
77 XBT_PUBLIC(void) xbt_free_f(void* p) {
82 /* TSC (tick-level) timers are said to be unreliable on SMP hosts and thus
83 disabled in SDL source code */
86 /* \defgroup XBT_sysdep All system dependency
87 * \brief This section describes many macros/functions that can serve as
92 struct s_xbt_os_timer {
93 #ifdef HAVE_GETTIMEOFDAY
94 struct timeval start,stop;
96 unsigned long int start,stop;
100 xbt_os_timer_t xbt_os_timer_new(void) {
101 return xbt_new0(struct s_xbt_os_timer,1);
103 void xbt_os_timer_free(xbt_os_timer_t timer) {
106 void xbt_os_timer_start(xbt_os_timer_t timer) {
107 #ifdef HAVE_GETTIMEOFDAY
108 gettimeofday(&(timer->start), NULL);
110 timer->start = (unsigned long int)(time(NULL));
113 void xbt_os_timer_stop(xbt_os_timer_t timer) {
114 #ifdef HAVE_GETTIMEOFDAY
115 gettimeofday(&(timer->stop), NULL);
117 timer->stop = (unsigned long int)(time(NULL));
120 double xbt_os_timer_elapsed(xbt_os_timer_t timer) {
121 #ifdef HAVE_GETTIMEOFDAY
122 return ((double)timer->stop.tv_sec) - ((double)timer->start.tv_sec) +
123 ((((double)timer->stop.tv_usec) - ((double)timer->start.tv_usec)) / 1000000.0);
125 return (double)timer->stop - (double)timer->start;