stop_watch.hpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*=============================================================================
  2. Boost.Wave: A Standard compliant C++ preprocessor library
  3. http://www.boost.org/
  4. Copyright (c) 2001-2012 Hartmut Kaiser. Distributed under the Boost
  5. Software License, Version 1.0. (See accompanying file
  6. LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. =============================================================================*/
  8. #if !defined(STOP_WATCH_HPP_HK040911_INCLUDED)
  9. #define STOP_WATCH_HPP_HK040911_INCLUDED
  10. #include <boost/config.hpp>
  11. #include <boost/timer.hpp>
  12. ///////////////////////////////////////////////////////////////////////////////
  13. //
  14. class stop_watch : public boost::timer {
  15. typedef boost::timer base_t;
  16. public:
  17. stop_watch() : is_suspended_since(0), suspended_overall(0) {}
  18. void suspend()
  19. {
  20. if (0 == is_suspended_since) {
  21. // if not already suspended
  22. is_suspended_since = this->base_t::elapsed();
  23. }
  24. }
  25. void resume()
  26. {
  27. if (0 != is_suspended_since) {
  28. // if really suspended
  29. suspended_overall += this->base_t::elapsed() - is_suspended_since;
  30. is_suspended_since = 0;
  31. }
  32. }
  33. double elapsed() const
  34. {
  35. if (0 == is_suspended_since) {
  36. // currently running
  37. return this->base_t::elapsed() - suspended_overall;
  38. }
  39. // currently suspended
  40. BOOST_ASSERT(is_suspended_since >= suspended_overall);
  41. return is_suspended_since - suspended_overall;
  42. }
  43. std::string format_elapsed_time() const
  44. {
  45. double current = elapsed();
  46. char time_buffer[sizeof("1234:56:78.90 abcd.")+1];
  47. using namespace std;
  48. if (current >= 3600) {
  49. // show hours
  50. sprintf (time_buffer, "%d:%02d:%02d.%03d hrs.",
  51. (int)(current) / 3600, ((int)(current) % 3600) / 60,
  52. ((int)(current) % 3600) % 60,
  53. (int)(current * 1000) % 1000);
  54. }
  55. else if (current >= 60) {
  56. // show minutes
  57. sprintf (time_buffer, "%d:%02d.%03d min.",
  58. (int)(current) / 60, (int)(current) % 60,
  59. (int)(current * 1000) % 1000);
  60. }
  61. else {
  62. // show seconds
  63. sprintf(time_buffer, "%d.%03d sec.", (int)current,
  64. (int)(current * 1000) % 1000);
  65. }
  66. return time_buffer;
  67. }
  68. private:
  69. double is_suspended_since;
  70. double suspended_overall;
  71. };
  72. #endif // !defined(STOP_WATCH_HPP_HK040911_INCLUDED)