/xapian-core/tests/harness/cputimer.cc

https://github.com/estrai/xapian · C++ · 93 lines · 61 code · 10 blank · 22 comment · 7 complexity · b75d471ced017ff4807fa6d2ad39b364 MD5 · raw file

  1. /** @file cputimer.cc
  2. * @brief Measure CPU time.
  3. */
  4. /* Copyright (C) 2009 Olly Betts
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License as
  8. * published by the Free Software Foundation; either version 2 of the
  9. * License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <config.h>
  21. #include "cputimer.h"
  22. #include "testsuite.h"
  23. #include "safeerrno.h"
  24. #ifdef HAVE_GETRUSAGE
  25. # include <sys/time.h>
  26. # include <sys/resource.h>
  27. #elif defined HAVE_TIMES
  28. # include <sys/times.h>
  29. # ifdef HAVE_SYSCONF
  30. # include "safeunistd.h"
  31. # endif
  32. #elif defined HAVE_FTIME
  33. # include <sys/timeb.h>
  34. #else
  35. # include <ctime>
  36. #endif
  37. #include <cstring>
  38. #include <string>
  39. using namespace std;
  40. double
  41. CPUTimer::get_current_cputime() const
  42. {
  43. double t = 0;
  44. #ifdef HAVE_GETRUSAGE
  45. struct rusage r;
  46. if (getrusage(RUSAGE_SELF, &r) == -1) {
  47. FAIL_TEST(string("Couldn't measure CPU for self: ") + strerror(errno));
  48. }
  49. t = r.ru_utime.tv_sec + r.ru_stime.tv_sec;
  50. t += (r.ru_utime.tv_usec + r.ru_stime.tv_usec) * 0.000001;
  51. #elif defined HAVE_TIMES
  52. struct tms b;
  53. if (times(&b) == (clock_t)-1) {
  54. FAIL_TEST(string("Couldn't measure CPU: ") + strerror(errno));
  55. }
  56. t = (double)(b.tms_utime + b.tms_stime);
  57. # ifdef HAVE_SYSCONF
  58. t /= sysconf(_SC_CLK_TCK);
  59. # else
  60. t /= CLK_TCK;
  61. # endif
  62. #else
  63. // FIXME: Fallback to just using wallclock time, which is probably only
  64. // going to be used on Microsoft Windows, where nobody has implemented
  65. // the code required to get the CPU time used by a process.
  66. # ifdef HAVE_FTIME
  67. struct timeb tb;
  68. # ifdef FTIME_RETURNS_VOID
  69. ftime(&tb);
  70. t = tb.time + (tb.millitm * 0.001);
  71. # else
  72. if (ftime(&tb) == -1) {
  73. t = time(NULL);
  74. } else {
  75. t = tb.time + (tb.millitm * 0.001);
  76. }
  77. # endif
  78. # else
  79. t = time(NULL);
  80. # endif
  81. #endif
  82. return t;
  83. }