CStopWatch.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * CStopWatch.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  12. #include <sys/types.h>
  13. #include <sys/time.h>
  14. #include <sys/resource.h>
  15. #define TO_MS_DIVISOR (1000)
  16. #else
  17. #include <ctime>
  18. #define TO_MS_DIVISOR (CLOCKS_PER_SEC / 1000)
  19. #endif
  20. VCMI_LIB_NAMESPACE_BEGIN
  21. class CStopWatch
  22. {
  23. si64 start;
  24. si64 last;
  25. si64 mem;
  26. public:
  27. CStopWatch()
  28. : start(clock())
  29. {
  30. last=clock();
  31. mem=0;
  32. }
  33. si64 getDiff() //get diff in milliseconds
  34. {
  35. si64 ret = clock() - last;
  36. last = clock();
  37. return ret / TO_MS_DIVISOR;
  38. }
  39. void update()
  40. {
  41. last=clock();
  42. }
  43. void remember()
  44. {
  45. mem=clock();
  46. }
  47. si64 memDif()
  48. {
  49. return (clock()-mem) / TO_MS_DIVISOR;
  50. }
  51. private:
  52. si64 clock()
  53. {
  54. #if defined(__FreeBSD__) || defined(__OpenBSD__) // TODO: enable also for Apple?
  55. struct rusage usage;
  56. getrusage(RUSAGE_SELF, &usage);
  57. return static_cast<si64>(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) * 1000000 + usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
  58. #else
  59. return std::clock();
  60. #endif
  61. }
  62. };
  63. VCMI_LIB_NAMESPACE_END