timeval.c

Go to the documentation of this file.
00001 /* * 
00002  * This file is part of libnemesi
00003  *
00004  * Copyright (C) 2007 by LScube team <team@streaming.polito.it>
00005  * See AUTHORS for more details
00006  * 
00007  * libnemesi is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * libnemesi is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with libnemesi; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  *  
00021  * */
00022 
00023 //XXX get a saner implementation.
00024 
00029 #include "utils.h"
00030 
00038 int nms_timeval_add(struct timeval *res, const struct timeval *x,
00039         const struct timeval *y)
00040 {
00041     res->tv_sec = x->tv_sec + y->tv_sec;
00042 
00043     res->tv_usec = x->tv_usec + y->tv_usec;
00044 
00045     if (res->tv_usec > 1000000) {
00046         res->tv_usec -= 1000000;
00047         res->tv_sec++;
00048     }
00049 
00050     return 0;
00051 }
00052 
00060 int nms_timeval_subtract(struct timeval *res, const struct timeval *x,
00061              const struct timeval *y)
00062 {
00063     int nsec;
00064     struct timeval z = *y;
00065 
00066     /* Perform the carry for the later subtraction by updating Y. */
00067     if (x->tv_usec < z.tv_usec) {
00068         nsec = (z.tv_usec - x->tv_usec) / 1000000 + 1;
00069         z.tv_usec -= 1000000 * nsec;
00070         z.tv_sec += nsec;
00071     }
00072     if (x->tv_usec - z.tv_usec > 1000000) {
00073         nsec = (x->tv_usec - z.tv_usec) / 1000000;
00074         z.tv_usec += 1000000 * nsec;
00075         z.tv_sec -= nsec;
00076     }
00077 
00078     /* Compute the time remaining to wait.
00079      * `tv_usec' is certainly positive. */
00080     if (res != NULL) {
00081         res->tv_sec = x->tv_sec - z.tv_sec;
00082         res->tv_usec = x->tv_usec - z.tv_usec;
00083     }
00084 
00085     /* Return 1 if result is negative (x < y).  */
00086     return ((x->tv_sec < z.tv_sec)
00087         || ((x->tv_sec == z.tv_sec) && (x->tv_usec < z.tv_usec)));
00088 }
00089 
00090 /*
00091  * Convert a float value (seconds) to a timeval
00092  */
00093 
00094 void f2time(double ftime, struct timeval *time)
00095 {
00096     time->tv_sec = (long) ftime;
00097     time->tv_usec = (long) ((ftime - time->tv_sec) * 1000000);
00098 }

Generated on Tue Feb 3 03:10:02 2009 for libnemesi by  doxygen 1.5.4