1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "Timer.hpp"
16 
17 #if defined(_WIN32)
18 	#ifndef WIN32_LEAN_AND_MEAN
19 		#define WIN32_LEAN_AND_MEAN
20 	#endif
21 	#include <windows.h>
22 #else
23 	#include <sys/time.h>
24 	#include <x86intrin.h>
25 #endif
26 
27 namespace sw
28 {
Timer()29 	Timer::Timer()
30 	{
31 	}
32 
~Timer()33 	Timer::~Timer()
34 	{
35 	}
36 
seconds()37 	double Timer::seconds()
38 	{
39 		#if defined(_WIN32)
40 			return (double)counter() / (double)frequency();
41 		#else
42 			timeval t;
43 			gettimeofday(&t, 0);
44 			return (double)t.tv_sec + (double)t.tv_usec * 1.0e-6;
45 		#endif
46 	}
47 
ticks()48 	int64_t Timer::ticks()
49 	{
50 		#if defined(_WIN32)
51 			return __rdtsc();
52 		#else
53 			int64_t tsc;
54 			__asm volatile("rdtsc": "=A" (tsc));
55 			return tsc;
56 		#endif
57 	}
58 
counter()59 	int64_t Timer::counter()
60 	{
61 		#if defined(_WIN32)
62 			int64_t counter;
63 			QueryPerformanceCounter((LARGE_INTEGER*)&counter);
64 			return counter;
65 		#else
66 			timeval t;
67 			gettimeofday(&t, 0);
68 			return t.tv_sec * 1000000 + t.tv_usec;
69 		#endif
70 	}
71 
frequency()72 	int64_t Timer::frequency()
73 	{
74 		#if defined(_WIN32)
75 			int64_t frequency;
76 			QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
77 			return frequency;
78 		#else
79 			return 1000000;   // gettimeofday uses microsecond resolution
80 		#endif
81 	}
82 }
83