file timer brief various timer functions compile with -lrt -lm run fro

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*! \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 <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
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);
}