rdtsc.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2010 Google Inc. 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. // Reads CPU cycle counter on AMD64 and I386 (for performance measurements).
  15. // Thanks to __rdtsc() intrinsic, it's easy with Microsoft and Intel
  16. // compilers, but real pain with GCC.
  17. #ifndef CRCUTIL_RDTSC_H_
  18. #define CRCUTIL_RDTSC_H_
  19. #include "platform.h"
  20. namespace crcutil {
  21. struct Rdtsc {
  22. static inline uint64 Get() {
  23. #if defined(_MSC_VER) && (HAVE_AMD64 || HAVE_I386)
  24. return __rdtsc();
  25. #elif defined(__GNUC__) && HAVE_AMD64
  26. int64 result;
  27. __asm__ volatile(
  28. "rdtsc\n"
  29. : "=a" (result));
  30. return result;
  31. #elif defined(__GNUC__) && HAVE_I386
  32. // If "low" and "high" are defined as "uint64" to
  33. // avoid explicit cast to uint64, GCC 4.5.0 in "-m32" mode
  34. // fails with "impossible register constraint" error
  35. // (no, it is not because one cannot use 64-bit value as argument
  36. // for 32-bit register, but because its register allocator
  37. // could not resolve a conflict under high register pressure).
  38. uint32 low;
  39. uint32 high;
  40. __asm__ volatile(
  41. "rdtsc\n"
  42. : "=a" (low), "=d" (high));
  43. return ((static_cast<uint64>(high) << 32) | low);
  44. #else
  45. // It is hard to find low overhead timer with
  46. // sub-millisecond resolution and granularity.
  47. return 0;
  48. #endif
  49. }
  50. };
  51. } // namespace crcutil
  52. #endif // CRCUTIL_RDTSC_H_