SysTime.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2016-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/portability/SysTime.h>
  17. #ifdef _WIN32
  18. #include <cstdint>
  19. extern "C" {
  20. int gettimeofday(timeval* tv, struct timezone*) {
  21. constexpr auto posixWinFtOffset = 116444736000000000ULL;
  22. if (tv) {
  23. FILETIME ft;
  24. ULARGE_INTEGER lft;
  25. GetSystemTimeAsFileTime(&ft);
  26. // As per the docs of FILETIME, don't just do an indirect
  27. // pointer cast, to avoid alignment faults.
  28. lft.HighPart = ft.dwHighDateTime;
  29. lft.LowPart = ft.dwLowDateTime;
  30. uint64_t ns = lft.QuadPart;
  31. tv->tv_usec = (long)((ns / 10ULL) % 1000000ULL);
  32. tv->tv_sec = (long)((ns - posixWinFtOffset) / 10000000ULL);
  33. }
  34. return 0;
  35. }
  36. void timeradd(timeval* a, timeval* b, timeval* res) {
  37. res->tv_sec = a->tv_sec + b->tv_sec;
  38. res->tv_usec = a->tv_usec + b->tv_usec;
  39. if (res->tv_usec >= 1000000) {
  40. res->tv_sec++;
  41. res->tv_usec -= 1000000;
  42. }
  43. }
  44. void timersub(timeval* a, timeval* b, timeval* res) {
  45. res->tv_sec = a->tv_sec - b->tv_sec;
  46. res->tv_usec = a->tv_usec - b->tv_usec;
  47. if (res->tv_usec < 0) {
  48. res->tv_sec--;
  49. res->tv_usec += 1000000;
  50. }
  51. }
  52. }
  53. #endif