A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
time.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2005,2006 INRIA
3 * Copyright (c) 2007 Emmanuelle Laprise
4 *
5 * SPDX-License-Identifier: GPL-2.0-only
6 *
7 * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
8 * TimeStep support by Emmanuelle Laprise <emmanuelle.laprise@bluekazoo.ca>
9 */
10#include "abort.h"
11#include "log.h"
12#include "nstime.h"
13
14#include <cmath> // pow
15#include <mutex>
16#include <sstream>
17
18/**
19 * @file
20 * @ingroup time
21 * ns3::Time, ns3::TimeWithUnit
22 * and ns3::TimeValue attribute value implementations.
23 */
24
25namespace ns3
26{
27
29
30/** Unnamed namespace */
31namespace
32{
33
34/** Scaling coefficients, exponents, and look up table for unit. */
35/** @{ */
36/** Scaling exponent, relative to smallest unit. */
37// Y, D, H, MIN, S, MS, US, NS, PS, FS
38const int8_t UNIT_POWER[Time::LAST] = {17, 17, 17, 16, 15, 12, 9, 6, 3, 0};
39/** Scaling coefficient, relative to smallest unit. */
40const int32_t UNIT_COEFF[Time::LAST] = {315360, 864, 36, 6, 1, 1, 1, 1, 1, 1};
41
42/**
43 * Scale a unit to the smallest unit.
44 * @param u The unit to scale
45 * @returns The value of \pname{u} in terms of the smallest defined unit.
46 */
47long double
49{
50 return UNIT_COEFF[u] * std::pow(10.0L, UNIT_POWER[u]);
51}
52
53/**
54 * Initializer for \c UNIT_VALUE
55 * @returns The array of scale factors between units.
56 */
57long double*
59{
60 static long double values[Time::LAST];
61 for (auto u = static_cast<int>(Time::Y); u != static_cast<int>(Time::LAST); ++u)
62 {
63 values[u] = Scale(static_cast<Time::Unit>(u));
64 }
65 return values;
66}
67
68/** Value of each unit, in terms of the smallest defined unit. */
69const long double* UNIT_VALUE = InitUnitValue();
70
71/** @} */
72
73} // unnamed namespace
74
75// The set of marked times
76// static
78
79/**
80 * Get the mutex for critical sections around modification of Time::g_markingTimes.
81 *
82 * Constructed on first use, since Time::StaticInit() runs during static
83 * initialization of other compilation units, and std::mutex is not
84 * constant-initialized on every platform (e.g. MinGW).
85 *
86 * @return The marking mutex.
87 */
88static std::mutex&
90{
91 static std::mutex mutex;
92 return mutex;
93}
94
95// Function called to force static initialization
96// static
97bool
99{
100 static bool firstTime = true;
101
102 std::unique_lock lock{MarkingMutex()};
103
104 if (firstTime)
105 {
106 if (!g_markingTimes)
107 {
108 static MarkedTimes markingTimes;
109 g_markingTimes = &markingTimes;
110 }
111 else
112 {
113 NS_LOG_ERROR("firstTime but g_markingTimes != 0");
114 }
115
116 // Schedule the cleanup.
117 // We'd really like:
118 // NS_LOG_LOGIC ("scheduling ClearMarkedTimes()");
119 // Simulator::Schedule ( Seconds (0), & ClearMarkedTimes);
120 // [or even better: Simulator::AtStart ( & ClearMarkedTimes ); ]
121 // But this triggers a static initialization order error,
122 // since the Simulator static initialization may not have occurred.
123 // Instead, we call ClearMarkedTimes directly from Simulator::Run ()
124 firstTime = false;
125 }
126
127 return firstTime;
128}
129
130Time::Time(const std::string& s)
131{
132 NS_LOG_FUNCTION(this << &s);
133 std::string::size_type n = s.find_first_not_of("+-0123456789.eE");
134 if (n != std::string::npos)
135 { // Found non-numeric
136 std::istringstream iss;
137 iss.str(s.substr(0, n));
138 double r;
139 iss >> r;
140 std::string trailer = s.substr(n, std::string::npos);
141 if (trailer == "s")
142 {
143 *this = Time::FromDouble(r, Time::S);
144 }
145 else if (trailer == "ms")
146 {
147 *this = Time::FromDouble(r, Time::MS);
148 }
149 else if (trailer == "us")
150 {
151 *this = Time::FromDouble(r, Time::US);
152 }
153 else if (trailer == "ns")
154 {
155 *this = Time::FromDouble(r, Time::NS);
156 }
157 else if (trailer == "ps")
158 {
159 *this = Time::FromDouble(r, Time::PS);
160 }
161 else if (trailer == "fs")
162 {
163 *this = Time::FromDouble(r, Time::FS);
164 }
165 else if (trailer == "min")
166 {
167 *this = Time::FromDouble(r, Time::MIN);
168 }
169 else if (trailer == "h")
170 {
171 *this = Time::FromDouble(r, Time::H);
172 }
173 else if (trailer == "d")
174 {
175 *this = Time::FromDouble(r, Time::D);
176 }
177 else if (trailer == "y")
178 {
179 *this = Time::FromDouble(r, Time::Y);
180 }
181 else
182 {
183 NS_ABORT_MSG("Can't Parse Time " << s);
184 }
185 }
186 else
187 {
188 // they didn't provide units, assume seconds
189 std::istringstream iss;
190 iss.str(s);
191 double v;
192 iss >> v;
193 *this = Time::FromDouble(v, Time::S);
194 }
195
196 if (MarkingTimes())
197 {
198 Mark(this);
199 }
200}
201
202// static
205{
207 static Resolution resolution;
208 SetResolution(Time::NS, &resolution, false);
209 return resolution;
210}
211
212// static
213void
215{
216 NS_LOG_FUNCTION(resolution);
217 SetResolution(resolution, PeekResolution());
218}
219
220// static
221void
222Time::SetResolution(Unit unit, Resolution* resolution, const bool convert /* = true */)
223{
224 NS_LOG_FUNCTION(resolution);
225 if (convert)
226 {
227 // We have to convert existing Times with the old
228 // conversion values, so do it first
229 ConvertTimes(unit);
230 }
231
232 for (int i = 0; i < Time::LAST; i++)
233 {
234 int shift = UNIT_POWER[i] - UNIT_POWER[unit];
235 int quotient = 1;
236 if (UNIT_COEFF[i] > UNIT_COEFF[unit])
237 {
238 quotient = UNIT_COEFF[i] / UNIT_COEFF[unit];
239 NS_ASSERT(quotient * UNIT_COEFF[unit] == UNIT_COEFF[i]);
240 }
241 else if (UNIT_COEFF[i] < UNIT_COEFF[unit])
242 {
243 quotient = UNIT_COEFF[unit] / UNIT_COEFF[i];
244 NS_ASSERT(quotient * UNIT_COEFF[i] == UNIT_COEFF[unit]);
245 }
246 NS_LOG_DEBUG("SetResolution for unit " << unit << " loop iteration " << i << " has shift "
247 << shift << " has quotient " << quotient);
248
249 Information* info = &resolution->info[i];
250 if ((std::pow(10.0, std::fabs(shift)) * quotient) >
251 static_cast<double>(std::numeric_limits<int64_t>::max()))
252 {
253 NS_LOG_DEBUG("SetResolution for unit " << unit << " loop iteration " << i
254 << " marked as INVALID");
255 info->isValid = false;
256 continue;
257 }
258 auto factor = static_cast<int64_t>(std::pow(10.0, std::fabs(shift)) * quotient);
259 double realFactor = std::pow(10.0, shift) * static_cast<double>(UNIT_COEFF[i]) /
260 UNIT_COEFF[static_cast<int>(unit)];
261 NS_LOG_DEBUG("SetResolution factor " << factor << " real factor " << realFactor);
262 info->factor = factor;
263 // here we could equivalently check for realFactor == 1.0 but it's better
264 // to avoid checking equality of doubles
265 if (shift == 0 && quotient == 1)
266 {
267 info->timeFrom = int64x64_t(1);
268 info->timeTo = int64x64_t(1);
269 info->toMul = true;
270 info->fromMul = true;
271 info->isValid = true;
272 }
273 else if (realFactor > 1)
274 {
275 info->timeFrom = int64x64_t(factor);
276 info->timeTo = int64x64_t::Invert(factor);
277 info->toMul = false;
278 info->fromMul = true;
279 info->isValid = true;
280 }
281 else
282 {
283 NS_ASSERT(realFactor < 1);
284 info->timeFrom = int64x64_t::Invert(factor);
285 info->timeTo = int64x64_t(factor);
286 info->toMul = true;
287 info->fromMul = false;
288 info->isValid = true;
289 }
290 }
291 resolution->unit = unit;
292}
293
294#ifdef _WIN32
295bool
297{
298 return (g_markingTimes != nullptr);
299}
300#endif
301
302// static
303void
305{
306 /**
307 * @internal
308 *
309 * We're called by Simulator::Run, which knows nothing about the mutex,
310 * so we need a critical section here.
311 *
312 * It would seem natural to use this function at the end of
313 * ConvertTimes, but that function already has the mutex.
314 * The mutex can not be locked more than once in the same thread,
315 * so calling this function from ConvertTimes is a bad idea.
316 *
317 * Instead, we copy this body into ConvertTimes.
318 */
319
320 std::unique_lock lock{MarkingMutex()};
321
323 if (g_markingTimes)
324 {
325 NS_LOG_LOGIC("clearing MarkedTimes");
326 g_markingTimes->erase(g_markingTimes->begin(), g_markingTimes->end());
327 g_markingTimes = nullptr;
328 }
329}
330
331// static
332void
333Time::Mark(Time* const time)
334{
335 std::unique_lock lock{MarkingMutex()};
336
337 NS_LOG_FUNCTION(time);
338 NS_ASSERT(time != nullptr);
339
340 // Repeat the g_markingTimes test here inside the CriticalSection,
341 // since earlier test was outside and might be stale.
342 if (g_markingTimes)
343 {
344 auto ret = g_markingTimes->insert(time);
345 NS_LOG_LOGIC("\t[" << g_markingTimes->size() << "] recording " << time);
346
347 if (!ret.second)
348 {
349 NS_LOG_WARN("already recorded " << time << "!");
350 }
351 }
352}
353
354// static
355void
356Time::Clear(Time* const time)
357{
358 std::unique_lock lock{MarkingMutex()};
359
360 NS_LOG_FUNCTION(time);
361 NS_ASSERT(time != nullptr);
362
363 if (g_markingTimes)
364 {
365 NS_ASSERT_MSG(g_markingTimes->count(time) == 1,
366 "Time object " << time << " registered " << g_markingTimes->count(time)
367 << " times (should be 1).");
368
369 MarkedTimes::size_type num = g_markingTimes->erase(time);
370 if (num != 1)
371 {
372 NS_LOG_WARN("unexpected result erasing " << time << "!");
373 NS_LOG_WARN("got " << num << ", expected 1");
374 }
375 else
376 {
377 NS_LOG_LOGIC("\t[" << g_markingTimes->size() << "] removing " << time);
378 }
379 }
380}
381
382// static
383void
385{
386 std::unique_lock lock{MarkingMutex()};
387
389
390 NS_ASSERT_MSG(g_markingTimes != nullptr,
391 "No MarkedTimes registry. "
392 "Time::SetResolution () called more than once?");
393
394 for (auto it = g_markingTimes->begin(); it != g_markingTimes->end(); it++)
395 {
396 Time* const tp = *it;
397 if (!(tp->m_data == std::numeric_limits<int64_t>::min() ||
398 tp->m_data == std::numeric_limits<int64_t>::max()))
399 {
400 tp->m_data = tp->ToInteger(unit);
401 }
402 }
403
404 NS_LOG_LOGIC("logged " << g_markingTimes->size() << " Time objects.");
405
406 // Body of ClearMarkedTimes
407 // Assert above already guarantees g_markingTimes != 0
408 NS_LOG_LOGIC("clearing MarkedTimes");
409 g_markingTimes->erase(g_markingTimes->begin(), g_markingTimes->end());
410 g_markingTimes = nullptr;
411}
412
413// static
416{
417 // No function log b/c it interferes with operator<<
418 return PeekResolution()->unit;
419}
420
422Time::As(const Unit unit /* = Time::AUTO */) const
423{
424 return TimeWithUnit(*this, unit);
425}
426
427std::ostream&
428operator<<(std::ostream& os, const Time& time)
429{
430 os << time.As(Time::GetResolution());
431 return os;
432}
433
434std::ostream&
435operator<<(std::ostream& os, const TimeWithUnit& timeU)
436{
437 std::string label;
438 Time::Unit unit = timeU.m_unit;
439
440 if (unit == Time::AUTO)
441 {
442 auto value = static_cast<long double>(timeU.m_time.GetTimeStep());
443 // convert to finest scale (fs)
444 value *= Scale(Time::GetResolution());
445 // find the best unit
446 int u = Time::Y;
447 while (u != Time::LAST && UNIT_VALUE[u] > value)
448 {
449 ++u;
450 }
451 if (u == Time::LAST)
452 {
453 --u;
454 }
455 unit = static_cast<Time::Unit>(u);
456 }
457
458 switch (unit)
459 {
460 case Time::Y:
461 label = "y";
462 break;
463 case Time::D:
464 label = "d";
465 break;
466 case Time::H:
467 label = "h";
468 break;
469 case Time::MIN:
470 label = "min";
471 break;
472 case Time::S:
473 label = "s";
474 break;
475 case Time::MS:
476 label = "ms";
477 break;
478 case Time::US:
479 label = "us";
480 break;
481 case Time::NS:
482 label = "ns";
483 break;
484 case Time::PS:
485 label = "ps";
486 break;
487 case Time::FS:
488 label = "fs";
489 break;
490
491 case Time::LAST:
492 case Time::AUTO:
493 default:
494 NS_ABORT_MSG("can't be reached");
495 label = "unreachable";
496 break;
497 }
498
499 double v = timeU.m_time.ToDouble(unit);
500
501 // Note: we must copy the "original" format flags because we have to modify them.
502 // std::ios_base::showpos is to print the "+" in front of the number for positive,
503 // std::ios_base::right is to add (eventual) extra space in front of the number.
504 // the eventual extra space might be due to a std::setw (_number_), and
505 // normally it would be printed after the number and before the time unit label.
506
507 std::ios_base::fmtflags ff = os.flags();
508
509 os << std::showpos << std::right << v << label;
510
511 // And here we have to restore what we changed.
512 if (!(ff & std::ios_base::showpos))
513 {
514 os << std::noshowpos;
515 }
516 if (ff & std::ios_base::left)
517 {
518 os << std::left;
519 }
520 else if (ff & std::ios_base::internal)
521 {
522 os << std::internal;
523 }
524
525 return os;
526}
527
528std::istream&
529operator>>(std::istream& is, Time& time)
530{
531 std::string value;
532 is >> value;
533 time = Time(value);
534 return is;
535}
536
538
540MakeTimeChecker(const Time min, const Time max)
541{
542 NS_LOG_FUNCTION(min << max);
543
544 struct Checker : public AttributeChecker
545 {
546 Checker(const Time minValue, const Time maxValue)
547 : m_minValue(minValue),
548 m_maxValue(maxValue)
549 {
550 }
551
552 bool Check(const AttributeValue& value) const override
553 {
554 NS_LOG_FUNCTION(&value);
555 const auto v = dynamic_cast<const TimeValue*>(&value);
556 if (v == nullptr)
557 {
558 return false;
559 }
560 return v->Get() >= m_minValue && v->Get() <= m_maxValue;
561 }
562
563 std::string GetValueTypeName() const override
564 {
566 return "ns3::TimeValue";
567 }
568
569 bool HasUnderlyingTypeInformation() const override
570 {
572 return true;
573 }
574
575 std::string GetUnderlyingTypeInformation() const override
576 {
578 std::ostringstream oss;
579 oss << "Time " << m_minValue << ":" << m_maxValue;
580 return oss.str();
581 }
582
583 Ptr<AttributeValue> Create() const override
584 {
586 return ns3::Create<TimeValue>();
587 }
588
589 bool Copy(const AttributeValue& source, AttributeValue& destination) const override
590 {
591 NS_LOG_FUNCTION(&source << &destination);
592 const auto src = dynamic_cast<const TimeValue*>(&source);
593 auto dst = dynamic_cast<TimeValue*>(&destination);
594 if (src == nullptr || dst == nullptr)
595 {
596 return false;
597 }
598 *dst = *src;
599 return true;
600 }
601
602 Time m_minValue;
603 Time m_maxValue;
604 }* checker = new Checker(min, max);
605
606 return Ptr<const AttributeChecker>(checker, false);
607}
608
609} // namespace ns3
NS_ABORT_x macro definitions.
uint32_t r
uint32_t v
uint32_t u
uint32_t quotient
Represent the type of an attribute.
Definition attribute.h:157
Hold a value for an Attribute.
Definition attribute.h:59
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:70
Simulation virtual time values and global simulation resolution.
Definition nstime.h:95
Unit
The unit to use to interpret a number representing time.
Definition nstime.h:101
@ AUTO
auto-scale output when using Time::As()
Definition nstime.h:113
@ D
day, 24 hours
Definition nstime.h:103
@ US
microsecond
Definition nstime.h:108
@ PS
picosecond
Definition nstime.h:110
@ LAST
marker for last normal value
Definition nstime.h:112
@ Y
year, 365 days
Definition nstime.h:102
@ FS
femtosecond
Definition nstime.h:111
@ H
hour, 60 minutes
Definition nstime.h:104
@ MIN
minute, 60 seconds
Definition nstime.h:105
@ MS
millisecond
Definition nstime.h:107
@ S
second
Definition nstime.h:106
@ NS
nanosecond
Definition nstime.h:109
static void ClearMarkedTimes()
Remove all MarkedTimes.
Definition time.cc:304
static Resolution & SetDefaultNsResolution()
Set the default resolution.
Definition time.cc:204
TimeWithUnit As(const Unit unit=Time::AUTO) const
Attach a unit to a Time, to facilitate output in a specific unit.
Definition time.cc:422
static void ConvertTimes(const Unit unit)
Convert existing Times to the new unit.
Definition time.cc:384
static Unit GetResolution()
Definition time.cc:415
static bool StaticInit()
Function to force static initialization of Time.
Definition time.cc:98
static void Clear(Time *const time)
Remove a Time instance from the MarkedTimes, called by ~Time().
Definition time.cc:356
Time()
Default constructor, with value 0.
Definition nstime.h:128
static MarkedTimes * g_markingTimes
Record of outstanding Time objects which will need conversion when the resolution is set.
Definition nstime.h:763
int64_t m_data
Virtual time value, in the current unit.
Definition nstime.h:908
static Resolution * PeekResolution()
Get the current Resolution.
Definition nstime.h:696
static void Mark(Time *const time)
Record a Time instance with the MarkedTimes.
Definition time.cc:333
static void SetResolution(Unit resolution)
Definition time.cc:214
static bool MarkingTimes() noexcept
Null check for g_markingTimes from outside time.cc.
Definition nstime.h:784
int64_t ToInteger(Unit unit) const
Get the Time value expressed in a particular unit.
Definition nstime.h:568
static Time FromDouble(double value, Unit unit)
Create a Time equal to value in unit unit.
Definition nstime.h:517
double ToDouble(Unit unit) const
Get the Time value expressed in a particular unit.
Definition nstime.h:600
int64_t GetTimeStep() const
Get the raw time value, in the current resolution unit.
Definition nstime.h:440
std::set< Time * > MarkedTimes
Record all instances of Time, so we can rescale them when the resolution changes.
Definition nstime.h:748
A Time with attached unit, to facilitate output in that unit.
Definition nstime.h:1459
TimeWithUnit(const Time time, const Time::Unit unit)
Attach a unit to a Time.
Definition nstime.h:1467
Time m_time
The time.
Definition nstime.h:1474
Time::Unit m_unit
The unit to use in output.
Definition nstime.h:1475
High precision numerical type, implementing Q64.64 fixed precision.
static int64x64_t Invert(const uint64_t v)
Compute the inverse of an integer value.
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition assert.h:55
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition assert.h:76
#define ATTRIBUTE_VALUE_IMPLEMENT(type)
Define the class methods belonging to attribute value class typeValue for class type.
#define NS_ABORT_MSG(msg)
Unconditional abnormal program termination with a message.
Definition abort.h:38
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition log.h:253
#define NS_LOG_COMPONENT_DEFINE_MASK(name, mask)
Define a logging component with a mask.
Definition log.h:212
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:267
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition log.h:281
#define NS_LOG_FUNCTION_NOARGS()
Output the name of the function.
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
Definition log.h:260
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:492
Debug message logging.
const long double * UNIT_VALUE
Value of each unit, in terms of the smallest defined unit.
Definition time.cc:69
const int32_t UNIT_COEFF[Time::LAST]
Scaling coefficient, relative to smallest unit.
Definition time.cc:40
const int8_t UNIT_POWER[Time::LAST]
Scaling coefficients, exponents, and look up table for unit.
Definition time.cc:38
long double * InitUnitValue()
Initializer for UNIT_VALUE.
Definition time.cc:58
long double Scale(Time::Unit u)
Scale a unit to the smallest unit.
Definition time.cc:48
Every class exported by the ns3 library is enclosed in the ns3 namespace.
std::ostream & operator<<(std::ostream &os, const Angles &a)
Definition angles.cc:148
std::istream & operator>>(std::istream &is, Angles &a)
Definition angles.cc:172
static std::mutex & MarkingMutex()
Get the mutex for critical sections around modification of Time::g_markingTimes.
Definition time.cc:89
Ptr< T > Copy(Ptr< T > object)
Return a deep copy of a Ptr.
Definition ptr.h:667
@ LOG_PREFIX_TIME
Prefix all trace prints with simulation time.
Definition log.h:118
Ptr< const AttributeChecker > MakeTimeChecker()
Helper to make an unbounded Time checker.
Definition nstime.h:1436
Declaration of classes ns3::Time and ns3::TimeWithUnit, and the TimeValue implementation classes.
How to convert between other units and the current unit.
Definition nstime.h:675
int64_t factor
Ratio of this unit / current unit.
Definition nstime.h:678
bool toMul
Multiply when converting To, otherwise divide.
Definition nstime.h:676
int64x64_t timeFrom
Multiplier to convert from this unit.
Definition nstime.h:680
bool isValid
True if the current unit can be used.
Definition nstime.h:681
bool fromMul
Multiple when converting From, otherwise divide.
Definition nstime.h:677
int64x64_t timeTo
Multiplier to convert to this unit.
Definition nstime.h:679
Current time unit, and conversion info.
Definition nstime.h:686
Time::Unit unit
Current time unit.
Definition nstime.h:688
Information info[LAST]
Conversion info from current unit.
Definition nstime.h:687