1 // Copyright (c) 2011, Robert Escriva
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 //
7 //     * Redistributions of source code must retain the above copyright notice,
8 //       this list of conditions and the following disclaimer.
9 //     * Redistributions in binary form must reproduce the above copyright
10 //       notice, this list of conditions and the following disclaimer in the
11 //       documentation and/or other materials provided with the distribution.
12 //     * Neither the name of this project nor the names of its contributors may
13 //       be used to endorse or promote products derived from this software
14 //       without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 // POSSIBILITY OF SUCH DAMAGE.
27 
28 #ifndef e_timer_h_
29 #define e_timer_h_
30 
31 // C
32 #include <stdint.h>
33 
34 #if HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37 
38 #ifdef _MSC_VER
39 // Windows
40 #define _WINSOCKAPI_
41 #include <windows.h>
42 #endif
43 
44 //mach
45 #ifdef HAVE_MACH_ABSOLUTE_TIME
46 #include <mach/mach_time.h>
47 #endif
48 
49 // POSIX
50 #include <errno.h>
51 #include <time.h>
52 
53 // STL
54 #include <exception>
55 
56 // po6
57 #include <po6/error.h>
58 
59 // e
60 #include "e/time.h"
61 
62 uint64_t
time()63 e :: time()
64 {
65 #ifdef _MSC_VER
66     LARGE_INTEGER tickfreq, timestamp;
67     tickfreq.QuadPart = 0;
68     timestamp.QuadPart = 0;
69     QueryPerformanceFrequency((LARGE_INTEGER*)&tickfreq);
70     QueryPerformanceCounter((LARGE_INTEGER*)&timestamp);
71     return timestamp.QuadPart / (tickfreq.QuadPart/1000000000.0);
72 #elif defined HAVE_MACH_ABSOLUTE_TIME
73     mach_timebase_info_data_t info;
74     mach_timebase_info(&info);
75     return mach_absolute_time()*info.numer/info.denom;
76 #else
77     timespec ts;
78 
79     if (clock_gettime(CLOCK_REALTIME, &ts) < 0)
80     {
81         throw po6::error(errno);
82     }
83 
84     return ts.tv_sec * 1000000000 + ts.tv_nsec;
85 #endif
86 }
87 
88 #endif // e_timer_h__
89