CARLA
Time.h
Go to the documentation of this file.
1 // Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
2 // de Barcelona (UAB).
3 //
4 // This work is licensed under the terms of the MIT license.
5 // For a copy, see <https://opensource.org/licenses/MIT>.
6 
7 #pragma once
8 
9 #include "carla/Debug.h"
10 
11 #include <boost/date_time/posix_time/posix_time_types.hpp>
12 
13 #include <chrono>
14 
15 namespace carla {
16 
17  /// Positive time duration up to milliseconds resolution. Automatically casts
18  /// between std::chrono::duration and boost::posix_time::time_duration.
19  class time_duration {
20  public:
21 
22  static inline time_duration seconds(size_t timeout) {
23  return std::chrono::seconds(timeout);
24  }
25 
26  static inline time_duration milliseconds(size_t timeout) {
27  return std::chrono::milliseconds(timeout);
28  }
29 
30  constexpr time_duration() noexcept : _milliseconds(0u) {}
31 
32  template <typename Rep, typename Period>
33  time_duration(std::chrono::duration<Rep, Period> duration)
34  : _milliseconds([=]() {
35  const auto count = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
36  DEBUG_ASSERT(count >= 0);
37  return static_cast<size_t>(count);
38  }()) {}
39 
40  time_duration(boost::posix_time::time_duration timeout)
41  : time_duration(std::chrono::milliseconds(timeout.total_milliseconds())) {}
42 
43  time_duration(const time_duration &) = default;
44  time_duration &operator=(const time_duration &) = default;
45 
46  boost::posix_time::time_duration to_posix_time() const {
47  return boost::posix_time::milliseconds(_milliseconds);
48  }
49 
50  constexpr auto to_chrono() const {
51  return std::chrono::milliseconds(_milliseconds);
52  }
53 
54  operator boost::posix_time::time_duration() const {
55  return to_posix_time();
56  }
57 
58  constexpr size_t milliseconds() const noexcept {
59  return _milliseconds;
60  }
61 
62  private:
63 
64  size_t _milliseconds;
65  };
66 
67 } // namespace carla
static time_duration milliseconds(size_t timeout)
Definition: Time.h:26
boost::posix_time::time_duration to_posix_time() const
Definition: Time.h:46
time_duration(boost::posix_time::time_duration timeout)
Definition: Time.h:40
constexpr time_duration() noexcept
Definition: Time.h:30
This file contains definitions of common data structures used in traffic manager. ...
Definition: Carla.cpp:133
time_duration(std::chrono::duration< Rep, Period > duration)
Definition: Time.h:33
static time_duration seconds(size_t timeout)
Definition: Time.h:22
#define DEBUG_ASSERT(predicate)
Definition: Debug.h:66
constexpr size_t milliseconds() const noexcept
Definition: Time.h:58
time_duration & operator=(const time_duration &)=default
Positive time duration up to milliseconds resolution.
Definition: Time.h:19
constexpr auto to_chrono() const
Definition: Time.h:50
size_t _milliseconds
Definition: Time.h:64