File: stopwatch_test.cpp

package info (click to toggle)
libfplus 0.2.13-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,904 kB
  • sloc: cpp: 27,543; javascript: 634; sh: 105; python: 103; makefile: 6
file content (56 lines) | stat: -rw-r--r-- 1,433 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest/doctest.h"
#include <fplus/fplus.hpp>
#include <fplus/stopwatch.hpp>

using namespace std::chrono_literals;

template<typename Function>
auto invoke_n_times(int n, Function f)
{
  for (int i = 0; i < n; i++) {
    f();
  }
}

TEST_CASE("Timer, test_accuracy")
{
#ifdef NDEBUG  // only on release builds
  using namespace fplus;
  using namespace std::chrono_literals;

  auto measure_delta = []() {
    fplus::stopwatch t;
    std::this_thread::sleep_for(0.05s);
    auto duration = t.elapsed();
    auto delta = duration - 0.05;
    return fabs(delta);
  };

  // we ask for a sleep of 0.05s, but we will have a duration that can be higher
  // (up to 15 ms higher, since the cpu scheduler might switch to another process during this sleep)
  // to account for the cpu/task scheduler
  double max_acceptable_delta__task_scheduler = 0.02;

  // One run
  {
    auto delta = measure_delta();
    REQUIRE_LT(delta, max_acceptable_delta__task_scheduler);
  }

  // 10 consecutive runs (total duration = 0.5 seconds)
  {
    std::vector<double> deltas;
    invoke_n_times(10, [&]() {
      deltas.push_back(measure_delta());
    });
    auto mean_dev = fplus::mean_stddev<double>(deltas);
    REQUIRE_LT(mean_dev.first, 0.03);
    REQUIRE_LT(mean_dev.second, 0.01);
  }
#endif
}