STL_timer.hh 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //=====================================================
  2. // File : STL_Timer.hh
  3. // Author : L. Plagne <laurent.plagne@edf.fr)>
  4. // Copyright (C) EDF R&D, mar déc 3 18:59:35 CET 2002
  5. //=====================================================
  6. //
  7. // This program is free software; you can redistribute it and/or
  8. // modify it under the terms of the GNU General Public License
  9. // as published by the Free Software Foundation; either version 2
  10. // of the License, or (at your option) any later version.
  11. //
  12. // This program is distributed in the hope that it will be useful,
  13. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. // GNU General Public License for more details.
  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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. //
  20. // STL Timer Class. Adapted (L.P.) from the timer class by Musser et Al
  21. // described int the Book : STL Tutorial and reference guide.
  22. // Define a timer class for analyzing algorithm performance.
  23. #include <iostream>
  24. #include <iomanip>
  25. #include <vector>
  26. #include <map>
  27. #include <algorithm>
  28. using namespace std;
  29. class STL_Timer {
  30. public:
  31. STL_Timer(){ baseline = false; }; // Default constructor
  32. // Start a series of r trials:
  33. void start(unsigned int r){
  34. reps = r;
  35. count = 0;
  36. iterations.clear();
  37. iterations.reserve(reps);
  38. initial = time(0);
  39. };
  40. // Start a series of r trials to determine baseline time:
  41. void start_baseline(unsigned int r)
  42. {
  43. baseline = true;
  44. start(r);
  45. }
  46. // Returns true if the trials have been completed, else false
  47. bool check()
  48. {
  49. ++count;
  50. final = time(0);
  51. if (initial < final) {
  52. iterations.push_back(count);
  53. initial = final;
  54. count = 0;
  55. }
  56. return (iterations.size() < reps);
  57. };
  58. // Returns the results for external use
  59. double get_time( void )
  60. {
  61. sort(iterations.begin(), iterations.end());
  62. return 1.0/iterations[reps/2];
  63. };
  64. private:
  65. unsigned int reps; // Number of trials
  66. // For storing loop iterations of a trial
  67. vector<long> iterations;
  68. // For saving initial and final times of a trial
  69. time_t initial, final;
  70. // For counting loop iterations of a trial
  71. unsigned long count;
  72. // true if this is a baseline computation, false otherwise
  73. bool baseline;
  74. // For recording the baseline time
  75. double baseline_time;
  76. };