/*! \file timer.c * \brief various timer functions * compile with -lrt -lm * run from root */ /* (non-Doxygen) * Revision: none * Compiler: gcc * * Author: kuv (), ganqqwerty@bk.ru * Company: SIC ETU * * ===================================================================================== */ #include #include #include #include int main () { //===simple operations with time=== //current real time: time_t seconds = time(0); struct tm* currentTime = gmtime(&seconds); printf("%s", "Current time: \n"); //it's much easy and better that parsing by hands: printf("%s", asctime(currentTime)); struct tm* futureTime = malloc(sizeof (struct tm)); futureTime->tm_sec = 30; /* seconds */ futureTime->tm_min = 43; /* minutes */ futureTime->tm_hour = 22; /* hours */ futureTime->tm_mday = 20 ; /* day of the month */ futureTime->tm_mon = 1; /* month */ futureTime->tm_year = 112; /* year */ //let's try to change this pretty REAL time >:-] struct timespec futureTp; futureTp.tv_sec = mktime(futureTime); if (clock_settime(CLOCK_REALTIME,&futureTp)) printf("%s","Sorry, you are not root and you can't change calendar time.\n"); //checking results: struct timespec checkTp; clock_gettime(CLOCK_REALTIME, &checkTp); time_t newSeconds = checkTp.tv_sec; struct tm* newCurrentTime = gmtime(&newSeconds); printf("%s", "Changed time: \n"); printf("%s", asctime (newCurrentTime)); //===how much time do functions take?=== int howMuchTimes = 100500000; // in seconds, using time(): time_t beginTime, endTime; time(&beginTime); int i; for (i=0; i!=howMuchTimes; i++) sin(i); time(&endTime); double diff = difftime(endTime, beginTime); printf("%d sin in seconds : %.2lf \n", howMuchTimes , diff); //in mseconds using clock_gettime: struct timespec beginNanoTime, endNanoTime; clock_gettime(CLOCK_REALTIME, &beginNanoTime); for (i=0; i!=howMuchTimes; i++) sin(i); clock_gettime(CLOCK_REALTIME, &endNanoTime); double mSecDiff = (endNanoTime.tv_sec-beginNanoTime.tv_sec)*1000+fabs((endNanoTime.tv_nsec-beginNanoTime.tv_nsec)/1000000); printf("%.5lf \n ", mSecDiff); }