4 * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <sys/types.h>
39 gettimeofday(¤t_time, 0);
43 void Timer::subtract(int64_t value)
45 current_time.tv_usec += 1000 * (value % 1000);
46 current_time.tv_sec += value / 1000 + current_time.tv_usec / 1000000;
47 current_time.tv_usec %= 1000000;
48 if(get_difference() < 0) current_time = new_time;
51 int64_t Timer::get_difference(struct timeval *result)
53 gettimeofday(&new_time, 0);
55 result->tv_usec = new_time.tv_usec - current_time.tv_usec;
56 result->tv_sec = new_time.tv_sec - current_time.tv_sec;
57 if(result->tv_usec < 0)
59 result->tv_usec += 1000000;
63 return (int64_t)result->tv_sec * 1000 + (int64_t)result->tv_usec / 1000;
66 int64_t Timer::get_difference()
68 gettimeofday(&new_time, 0);
70 new_time.tv_usec -= current_time.tv_usec;
71 new_time.tv_sec -= current_time.tv_sec;
72 if(new_time.tv_usec < 0)
74 new_time.tv_usec += 1000000;
78 return (int64_t)new_time.tv_sec * 1000 +
79 (int64_t)new_time.tv_usec / 1000;
82 int64_t Timer::get_scaled_difference(long denominator)
84 get_difference(&new_time);
85 return (int64_t)new_time.tv_sec * denominator +
86 (int64_t)((double)new_time.tv_usec / 1000000 * denominator);
89 int Timer::delay(long milliseconds)
92 struct timeval delay_duration;
93 delay_duration.tv_sec = 0;
94 delay_duration.tv_usec = milliseconds * 1000;
95 select(0, NULL, NULL, NULL, &delay_duration);
97 struct timespec delay_duration;
98 delay_duration.tv_sec = milliseconds / 1000L;
99 delay_duration.tv_nsec = (milliseconds % 1000L) * 1000000L;
100 nanosleep(&delay_duration, 0);