1 /* ####################################################################### */
2 /* This script compares the speed of the computation of a polynomial       */
3 /* in C in a couple of different ways.                                     */
4 /*                                                                         */
5 /* Author: Francesc Alted                                                  */
6 /* Date: 2010-02-05                                                        */
7 /* ####################################################################### */
8 
9 
10 #include <stdio.h>
11 #include <math.h>
12 #if defined(_WIN32) && !defined(__MINGW32__)
13   #include <time.h>
14   #include <windows.h>
15 #else
16   #include <unistd.h>
17   #include <sys/time.h>
18 #endif
19 
20 
21 #define N  10*1000*1000
22 
23 double x[N];
24 double y[N];
25 
26 
27 #if defined(_WIN32) && !defined(__MINGW32__)
28 
29 #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
30   #define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
31 #else
32   #define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
33 #endif
34 
35 struct timezone
36 {
37   int  tz_minuteswest; /* minutes W of Greenwich */
38   int  tz_dsttime;     /* type of dst correction */
39 };
40 
gettimeofday(struct timeval * tv,struct timezone * tz)41 int gettimeofday(struct timeval *tv, struct timezone *tz)
42 {
43   FILETIME ft;
44   unsigned __int64 tmpres = 0;
45   static int tzflag;
46 
47   if (NULL != tv)
48   {
49     GetSystemTimeAsFileTime(&ft);
50 
51     tmpres |= ft.dwHighDateTime;
52     tmpres <<= 32;
53     tmpres |= ft.dwLowDateTime;
54 
55     /*converting file time to unix epoch*/
56     tmpres -= DELTA_EPOCH_IN_MICROSECS;
57     tmpres /= 10;  /*convert into microseconds*/
58     tv->tv_sec = (long)(tmpres / 1000000UL);
59     tv->tv_usec = (long)(tmpres % 1000000UL);
60   }
61 
62   if (NULL != tz)
63   {
64     if (!tzflag)
65     {
66       _tzset();
67       tzflag++;
68     }
69     tz->tz_minuteswest = _timezone / 60;
70     tz->tz_dsttime = _daylight;
71   }
72 
73   return 0;
74 }
75 #endif   /* _WIN32 */
76 
77 
78 /* Given two timeval stamps, return the difference in seconds */
getseconds(struct timeval last,struct timeval current)79 float getseconds(struct timeval last, struct timeval current) {
80   int sec, usec;
81 
82   sec = current.tv_sec - last.tv_sec;
83   usec = current.tv_usec - last.tv_usec;
84   return (float)(((double)sec + usec*1e-6));
85 }
86 
main(void)87 int main(void) {
88   int i;
89   double inf = -1;
90   struct timeval last, current;
91   float tspend;
92 
93   for(i=0; i<N; i++) {
94     x[i] = inf+(2.*i)/N;
95   }
96 
97   gettimeofday(&last, NULL);
98   for(i=0; i<N; i++) {
99     //y[i] = .25*pow(x[i],3.) + .75*pow(x[i],2.) - 1.5*x[i] - 2;
100     y[i] = ((.25*x[i] + .75)*x[i] - 1.5)*x[i] - 2;
101   }
102   gettimeofday(&current, NULL);
103   tspend = getseconds(last, current);
104   printf("Compute time:\t %.3fs\n", tspend);
105 
106 }
107