summaryrefslogtreecommitdiff
path: root/examples/cxx/tree/performance/time.cxx
blob: c91f813546ec29b4e5f38daee3e4975310463f1b (plain)
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
// file      : examples/cxx/tree/performance/time.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : not copyrighted - public domain

#include "time.hxx"

#if defined (WIN32) || defined (__WIN32__)
#  define WIN32_LEAN_AND_MEAN
#  include <windows.h>  // GetSystemTimeAsFileTime
#else
#  include <time.h>     // gettimeofday
#  include <sys/time.h> // timeval
#endif

#include <ostream> // std::ostream
#include <iomanip> // std::setfill, std::setw

namespace os
{
  time::
  time ()
  {
#if defined (WIN32) || defined (__WIN32__)
    FILETIME ft;
    GetSystemTimeAsFileTime (&ft);
    unsigned long long v (
      ((unsigned long long) (ft.dwHighDateTime) << 32) + ft.dwLowDateTime);

    sec_  = static_cast<unsigned long> (v / 10000000ULL);
    nsec_ = static_cast<unsigned long> ((v % 10000000ULL) * 100);
#else
    timeval tv;
    if (gettimeofday(&tv, 0) != 0)
      throw failed ();

    sec_  = static_cast<unsigned long> (tv.tv_sec);
    nsec_ = static_cast<unsigned long> (tv.tv_usec * 1000);
#endif
  }

  std::ostream&
  operator<< (std::ostream& o, time const& t)
  {
    return o << t.sec () << '.'
             << std::setfill ('0') << std::setw (9) << t.nsec ();
  }
}