gettimeofday.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "stdio.h"
  2. #include <time.h>
  3. #include <windows.h>
  4. #include <iostream>
  5. //using namespace System;
  6. using namespace std;
  7. #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
  8. #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
  9. #else
  10. #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
  11. #endif
  12. struct timezone
  13. {
  14. int tz_minuteswest; /* minutes W of Greenwich */
  15. int tz_dsttime; /* type of dst correction */
  16. };
  17. // Definition of a gettimeofday function
  18. int gettimeofday(struct timeval *tv, struct timezone *tz)
  19. {
  20. // Define a structure to receive the current Windows filetime
  21. FILETIME ft;
  22. // Initialize the present time to 0 and the timezone to UTC
  23. unsigned __int64 tmpres = 0;
  24. static int tzflag = 0;
  25. if (NULL != tv)
  26. {
  27. GetSystemTimeAsFileTime(&ft);
  28. // The GetSystemTimeAsFileTime returns the number of 100 nanosecond
  29. // intervals since Jan 1, 1601 in a structure. Copy the high bits to
  30. // the 64 bit tmpres, shift it left by 32 then or in the low 32 bits.
  31. tmpres |= ft.dwHighDateTime;
  32. tmpres <<= 32;
  33. tmpres |= ft.dwLowDateTime;
  34. // Convert to microseconds by dividing by 10
  35. tmpres /= 10;
  36. // The Unix epoch starts on Jan 1 1970. Need to subtract the difference
  37. // in seconds from Jan 1 1601.
  38. tmpres -= DELTA_EPOCH_IN_MICROSECS;
  39. // Finally change microseconds to seconds and place in the seconds value.
  40. // The modulus picks up the microseconds.
  41. tv->tv_sec = (long)(tmpres / 1000000UL);
  42. tv->tv_usec = (long)(tmpres % 1000000UL);
  43. }
  44. if (NULL != tz)
  45. {
  46. if (!tzflag)
  47. {
  48. _tzset();
  49. tzflag++;
  50. }
  51. // Adjust for the timezone west of Greenwich
  52. long seconds_diff;
  53. _get_timezone(&seconds_diff);
  54. tz->tz_minuteswest = seconds_diff / 60;
  55. int hours_offset;
  56. _get_daylight(&hours_offset);
  57. tz->tz_dsttime = hours_offset;
  58. }
  59. return 0;
  60. }