1 /* 2 * Copyright (c) 2009-2011, The Regents of the University of California, 3 * through Lawrence Berkeley National Laboratory (subject to receipt of any 4 * required approvals from the U.S. Dept. of Energy). All rights reserved. 5 * 6 * This code is distributed under a BSD style license, see the LICENSE file 7 * for complete information. 8 */ 9 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <string.h> 13 #include <errno.h> 14 #include <sys/time.h> 15 #include <sys/errno.h> 16 #include <sys/types.h> 17 #include <stdint.h> 18 #include <time.h> 19 20 #include "timer.h" 21 #include "iperf_api.h" 22 23 24 int 25 timer_expired(struct timer * tp) 26 { 27 if (tp == NULL) 28 return 0; 29 30 struct timeval now; 31 int64_t end = 0, current = 0; 32 33 gettimeofday(&now, NULL); 34 35 end += tp->end.tv_sec * 1000000; 36 end += tp->end.tv_usec; 37 38 current += now.tv_sec * 1000000; 39 current += now.tv_usec; 40 41 return current > end; 42 } 43 44 int 45 update_timer(struct timer * tp, time_t sec, suseconds_t usec) 46 { 47 if (gettimeofday(&tp->begin, NULL) < 0) { 48 i_errno = IEUPDATETIMER; 49 return (-1); 50 } 51 52 tp->end.tv_sec = tp->begin.tv_sec + (time_t) sec; 53 tp->end.tv_usec = tp->begin.tv_usec + (time_t) usec; 54 55 tp->expired = timer_expired; 56 return (0); 57 } 58 59 struct timer * 60 new_timer(time_t sec, suseconds_t usec) 61 { 62 struct timer *tp = NULL; 63 tp = (struct timer *) calloc(1, sizeof(struct timer)); 64 if (tp == NULL) { 65 i_errno = IENEWTIMER; 66 return (NULL); 67 } 68 69 if (gettimeofday(&tp->begin, NULL) < 0) { 70 i_errno = IENEWTIMER; 71 return (NULL); 72 } 73 74 tp->end.tv_sec = tp->begin.tv_sec + (time_t) sec; 75 tp->end.tv_usec = tp->begin.tv_usec + (time_t) usec; 76 77 tp->expired = timer_expired; 78 79 return tp; 80 } 81 82 void 83 free_timer(struct timer * tp) 84 { 85 free(tp); 86 } 87 88 89 int64_t 90 timer_remaining(struct timer * tp) 91 { 92 struct timeval now; 93 long int end_time = 0, current_time = 0, diff = 0; 94 95 gettimeofday(&now, NULL); 96 97 end_time += tp->end.tv_sec * 1000000; 98 end_time += tp->end.tv_usec; 99 100 current_time += now.tv_sec * 1000000; 101 current_time += now.tv_usec; 102 103 diff = end_time - current_time; 104 if (diff > 0) 105 return diff; 106 else 107 return 0; 108 } 109