CStopWatch.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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, last, mem;
  24. public:
  25. CStopWatch()
  26. : start(clock())
  27. {
  28. last=clock();
  29. mem=0;
  30. }
  31. si64 getDiff() //get diff in milliseconds
  32. {
  33. si64 ret = clock() - last;
  34. last = clock();
  35. return ret / TO_MS_DIVISOR;
  36. }
  37. void update()
  38. {
  39. last=clock();
  40. }
  41. void remember()
  42. {
  43. mem=clock();
  44. }
  45. si64 memDif()
  46. {
  47. return (clock()-mem) / TO_MS_DIVISOR;
  48. }
  49. private:
  50. si64 clock()
  51. {
  52. #if defined(__FreeBSD__) || defined(__OpenBSD__) // TODO: enable also for Apple?
  53. struct rusage usage;
  54. getrusage(RUSAGE_SELF, &usage);
  55. 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;
  56. #else
  57. return std::clock();
  58. #endif
  59. }
  60. };
  61. VCMI_LIB_NAMESPACE_END