source: trunk/src/time.cc @ 56

Last change on this file since 56 was 34, checked in by epyon, 12 years ago
  • time module added
File size: 2.4 KB
Line 
1// Copyright (C) 2011 Kornel Kisielewicz
2// This file is part of NV Libraries.
3// For conditions of distribution and use, see copyright notice in nv.hh
4
5#include "nv/time.hh"
6
7#include "nv/logging.hh"
8
9#if NV_COMPILER == NV_MSVC
10#define WIN32_LEAN_AND_MEAN
11#include <windows.h>
12#include <intrin.h>
13#pragma intrinsic(__rdtsc)
14#else
15#include <unistd.h>
16#include <sys/time.h>
17#endif
18
19#include <ctime>
20
21struct timer_impl
22{
23        timer_impl()
24        {
25                clock_zero = clock();
26#if NV_COMPILER == NV_MSVC
27                QueryPerformanceFrequency(&frequency);
28                QueryPerformanceCounter(&query_zero);
29#else
30                gettimeofday(&timeval_zero, NULL);
31#endif
32        }
33        clock_t clock_zero;
34#if NV_COMPILER == NV_MSVC
35        LARGE_INTEGER query_zero;
36        LARGE_INTEGER frequency;
37#else
38        struct timeval timeval_zero;
39#endif
40};
41
42static timer_impl zero_timer;
43
44volatile nv::uint64 nv::get_ticks()
45{
46#if NV_COMPILER == NV_MSVC
47        return __rdtsc();
48#elif NV_COMPILER == NV_GNUC
49        register long long ticks asm("eax");
50        asm volatile (".byte 15, 49" : : : "eax", "edx");
51        return ticks;
52#else
53        return 0; // unsupported
54#endif
55}
56
57void nv::sleep( uint32 ms )
58{
59#if NV_COMPILER == NV_MSVC
60        Sleep( ms );
61#elif NV_COMPILER == NV_GNUC
62        usleep( ms * 1000 );
63#else
64#endif
65}
66
67nv::uint32 nv::get_cpu_ms()
68{
69        return (uint32)( (f32)( clock() - zero_timer.clock_zero ) / ( (f32)CLOCKS_PER_SEC / 1000.0 ) ) ;
70}
71
72nv::uint32 nv::get_cpu_us()
73{
74        return (uint32)( (f32)( clock() - zero_timer.clock_zero ) / ( (f32)CLOCKS_PER_SEC / 1000000.0 ) ) ;
75}
76
77nv::uint32 nv::get_system_ms()
78{
79#if NV_COMPILER == NV_MSVC
80        LARGE_INTEGER now;
81        QueryPerformanceCounter(&now);
82        LONGLONG result = now.QuadPart - zero_timer.query_zero.QuadPart;
83        return (uint32) (1000.0 * result / zero_timer.frequency.QuadPart);
84#else
85        struct timeval now;
86        gettimeofday(&now, NULL);
87        return (now.tv_sec - zero_timer.timeval_zero.tv_sec)*1000+(now.tv_usec-zero_timer.timeval_zero.tv_usec)/1000;
88#endif
89}
90
91nv::uint32 nv::get_system_us()
92{
93#if NV_COMPILER == NV_MSVC
94        LARGE_INTEGER now;
95        QueryPerformanceCounter(&now);
96        LONGLONG result = now.QuadPart - zero_timer.query_zero.QuadPart;
97        return (uint32) (1000000.0 * result / zero_timer.frequency.QuadPart);
98#else
99        struct timeval now;
100        gettimeofday(&now, NULL);
101        return (now.tv_sec - zero_timer.timeval_zero.tv_sec)*1000000+(now.tv_usec - zero_timer.timeval_zero.tv_usec);
102#endif
103}
Note: See TracBrowser for help on using the repository browser.