Back to index

unity  6.0.0
TimeUtil.h
Go to the documentation of this file.
00001 // -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
00002 /*
00003  * Copyright (C) 2010 Canonical Ltd
00004  *
00005  * This program is free software: you can redistribute it and/or modify
00006  * it under the terms of the GNU General Public License version 3 as
00007  * published by the Free Software Foundation.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00016  *
00017  * Authored by: Jason Smith <jason.smith@canonical.com>
00018  * Authored by: Alex Launi <alex.launi@gmail.com>
00019  */
00020 
00021 #include <time.h>
00022 
00023 namespace unity {
00024 
00025 class TimeUtil
00026 {
00027 public:
00028   static int TimeDelta (struct timespec const* x, struct timespec const* y)
00029   {
00030     return ((x->tv_sec - y->tv_sec) * 1000) + ((x->tv_nsec - y->tv_nsec) / 1000000);
00031   }
00032 
00033   static void SetTimeStruct(struct timespec* timer, struct timespec* sister = 0, int sister_relation = 0)
00034   {
00035     struct timespec current;
00036     clock_gettime(CLOCK_MONOTONIC, &current);
00037 
00038     if (sister)
00039     {
00040       int diff = TimeDelta(&current, sister);
00041 
00042       if (diff < sister_relation)
00043       {
00044         int remove = sister_relation - diff;
00045         SetTimeBack(&current, remove);
00046       }
00047     }
00048 
00049     timer->tv_sec = current.tv_sec;
00050     timer->tv_nsec = current.tv_nsec;
00051   }
00052 
00053   static void SetTimeBack(struct timespec* timeref, int remove)
00054   {
00055     timeref->tv_sec -= remove / 1000;
00056     remove = remove % 1000;
00057 
00058     if (remove > timeref->tv_nsec / 1000000)
00059     {
00060       timeref->tv_sec--;
00061       timeref->tv_nsec += 1000000000;
00062     }
00063     timeref->tv_nsec -= remove * 1000000;
00064   }
00065 };
00066 
00067 
00068 }