A Discrete-Event Network Simulator
API
time.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2005,2006 INRIA
4  * Copyright (c) 2007 Emmanuelle Laprise
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation;
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  *
19  * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
20  * TimeStep support by Emmanuelle Laprise <emmanuelle.laprise@bluekazoo.ca>
21  */
22 #include "nstime.h"
23 #include "abort.h"
24 #include "system-mutex.h"
25 #include "log.h"
26 #include <cmath>
27 #include <iomanip> // showpos
28 #include <sstream>
29 
37 namespace ns3 {
38 
40 
41 // The set of marked times
42 // static
44 
53 SystemMutex &
55 {
56  static SystemMutex g_markingMutex;
57  return g_markingMutex;
58 }
59 
60 
61 // Function called to force static initialization
62 // static
64 {
65  static bool firstTime = true;
66 
67  CriticalSection critical (GetMarkingMutex ());
68 
69  if (firstTime)
70  {
71  if (! g_markingTimes)
72  {
73  static MarkedTimes markingTimes;
74  g_markingTimes = & markingTimes;
75  }
76  else
77  {
78  NS_LOG_ERROR ("firstTime but g_markingTimes != 0");
79  }
80 
81  // Schedule the cleanup.
82  // We'd really like:
83  // NS_LOG_LOGIC ("scheduling ClearMarkedTimes()");
84  // Simulator::Schedule ( Seconds (0), & ClearMarkedTimes);
85  // [or even better: Simulator::AtStart ( & ClearMarkedTimes ); ]
86  // But this triggers a static initialization order error,
87  // since the Simulator static initialization may not have occurred.
88  // Instead, we call ClearMarkedTimes directly from Simulator::Run ()
89  firstTime = false;
90  }
91 
92  return firstTime;
93 }
94 
95 
96 Time::Time (const std::string& s)
97 {
98  NS_LOG_FUNCTION (this << &s);
99  std::string::size_type n = s.find_first_not_of ("+-0123456789.eE");
100  if (n != std::string::npos)
101  { // Found non-numeric
102  std::istringstream iss;
103  iss.str (s.substr (0, n));
104  double r;
105  iss >> r;
106  std::string trailer = s.substr (n, std::string::npos);
107  if (trailer == std::string ("s"))
108  {
109  *this = Time::FromDouble (r, Time::S);
110  }
111  else if (trailer == std::string ("ms"))
112  {
113  *this = Time::FromDouble (r, Time::MS);
114  }
115  else if (trailer == std::string ("us"))
116  {
117  *this = Time::FromDouble (r, Time::US);
118  }
119  else if (trailer == std::string ("ns"))
120  {
121  *this = Time::FromDouble (r, Time::NS);
122  }
123  else if (trailer == std::string ("ps"))
124  {
125  *this = Time::FromDouble (r, Time::PS);
126  }
127  else if (trailer == std::string ("fs"))
128  {
129  *this = Time::FromDouble (r, Time::FS);
130  }
131  else if (trailer == std::string ("min"))
132  {
133  *this = Time::FromDouble (r, Time::MIN);
134  }
135  else if (trailer == std::string ("h"))
136  {
137  *this = Time::FromDouble (r, Time::H);
138  }
139  else if (trailer == std::string ("d"))
140  {
141  *this = Time::FromDouble (r, Time::D);
142  }
143  else if (trailer == std::string ("y"))
144  {
145  *this = Time::FromDouble (r, Time::Y);
146  }
147  else
148  {
149  NS_ABORT_MSG ("Can't Parse Time " << s);
150  }
151  }
152  else
153  {
154  // they didn't provide units, assume seconds
155  std::istringstream iss;
156  iss.str (s);
157  double v;
158  iss >> v;
159  *this = Time::FromDouble (v, Time::S);
160  }
161 
162  if (g_markingTimes)
163  {
164  Mark (this);
165  }
166 }
167 
168 // static
169 struct Time::Resolution
170 Time::SetDefaultNsResolution (void)
171 {
173  struct Resolution resolution;
174  SetResolution (Time::NS, &resolution, false);
175  return resolution;
176 }
177 
178 // static
179 void
180 Time::SetResolution (enum Unit resolution)
181 {
182  NS_LOG_FUNCTION (resolution);
183  SetResolution (resolution, PeekResolution ());
184 }
185 
186 
187 // static
188 void
189 Time::SetResolution (enum Unit unit, struct Resolution *resolution,
190  const bool convert /* = true */)
191 {
192  NS_LOG_FUNCTION (resolution);
193  if (convert)
194  {
195  // We have to convert existing Times with the old
196  // conversion values, so do it first
197  ConvertTimes (unit);
198  }
199 
200  // Y, D, H, MIN, S, MS, US, NS, PS, FS
201  const int8_t power [LAST] = { 17, 17, 17, 16, 15, 12, 9, 6, 3, 0 };
202  const int32_t coefficient [LAST] = { 315360, 864, 36, 6, 1, 1, 1, 1, 1, 1 };
203  for (int i = 0; i < Time::LAST; i++)
204  {
205  int shift = power[i] - power[(int)unit];
206  int quotient = 1;
207  if (coefficient[i] > coefficient[(int) unit])
208  {
209  quotient = coefficient[i] / coefficient[(int) unit];
210  NS_ASSERT (quotient * coefficient[(int) unit] == coefficient[i]);
211  }
212  else if (coefficient[i] < coefficient[(int) unit])
213  {
214  quotient = coefficient[(int) unit] / coefficient[i];
215  NS_ASSERT (quotient * coefficient[i] == coefficient[(int) unit]);
216  }
217  NS_LOG_DEBUG ("SetResolution for unit " << (int) unit << " loop iteration " << i
218  << " has shift " << shift << " has quotient " << quotient);
219  int64_t factor = static_cast<int64_t> (std::pow (10, std::fabs (shift)) * quotient);
220  double realFactor = std::pow (10, (double) shift)
221  * static_cast<double> (coefficient[i]) / coefficient[(int) unit];
222  NS_LOG_DEBUG ("SetResolution factor " << factor << " real factor " << realFactor);
223  struct Information *info = &resolution->info[i];
224  info->factor = factor;
225  // here we could equivalently check for realFactor == 1.0 but it's better
226  // to avoid checking equality of doubles
227  if (shift == 0 && quotient == 1)
228  {
229  info->timeFrom = int64x64_t (1);
230  info->timeTo = int64x64_t (1);
231  info->toMul = true;
232  info->fromMul = true;
233  }
234  else if (realFactor > 1)
235  {
236  info->timeFrom = int64x64_t (factor);
237  info->timeTo = int64x64_t::Invert (factor);
238  info->toMul = false;
239  info->fromMul = true;
240  }
241  else
242  {
243  NS_ASSERT (realFactor < 1);
244  info->timeFrom = int64x64_t::Invert (factor);
245  info->timeTo = int64x64_t (factor);
246  info->toMul = true;
247  info->fromMul = false;
248  }
249  }
250  resolution->unit = unit;
251 }
252 
253 
254 // static
255 void
257 {
273  CriticalSection critical (GetMarkingMutex ());
274 
276  if (g_markingTimes)
277  {
278  NS_LOG_LOGIC ("clearing MarkedTimes");
279  g_markingTimes->erase (g_markingTimes->begin(), g_markingTimes->end ());
280  g_markingTimes = 0;
281  }
282 } // Time::ClearMarkedTimes
283 
284 
285 // static
286 void
287 Time::Mark (Time * const time)
288 {
289  CriticalSection critical (GetMarkingMutex ());
290 
291  NS_LOG_FUNCTION (time);
292  NS_ASSERT (time != 0);
293 
294  // Repeat the g_markingTimes test here inside the CriticalSection,
295  // since earlier test was outside and might be stale.
296  if (g_markingTimes)
297  {
298  std::pair< MarkedTimes::iterator, bool> ret;
299 
300  ret = g_markingTimes->insert ( time);
301  NS_LOG_LOGIC ("\t[" << g_markingTimes->size () << "] recording " << time);
302 
303  if (ret.second == false)
304  {
305  NS_LOG_WARN ("already recorded " << time << "!");
306  }
307  }
308 } // Time::Mark ()
309 
310 
311 // static
312 void
313 Time::Clear (Time * const time)
314 {
315  CriticalSection critical (GetMarkingMutex ());
316 
317  NS_LOG_FUNCTION (time);
318  NS_ASSERT (time != 0);
319 
320  if (g_markingTimes)
321  {
322  NS_ASSERT_MSG (g_markingTimes->count (time) == 1,
323  "Time object " << time <<
324  " registered " << g_markingTimes->count (time) <<
325  " times (should be 1)." );
326 
327  MarkedTimes::size_type num = g_markingTimes->erase (time);
328  if (num != 1)
329  {
330  NS_LOG_WARN ("unexpected result erasing " << time << "!");
331  NS_LOG_WARN ("got " << num << ", expected 1");
332  }
333  else
334  {
335  NS_LOG_LOGIC ("\t[" << g_markingTimes->size () << "] removing " << time);
336  }
337  }
338 } // Time::Clear ()
339 
340 
341 // static
342 void
343 Time::ConvertTimes (const enum Unit unit)
344 {
345  CriticalSection critical (GetMarkingMutex ());
346 
348 
350  "No MarkedTimes registry. "
351  "Time::SetResolution () called more than once?");
352 
353  for ( MarkedTimes::iterator it = g_markingTimes->begin();
354  it != g_markingTimes->end();
355  it++ )
356  {
357  Time * const tp = *it;
358  if ( ! ( (tp->m_data == std::numeric_limits<int64_t>::min ())
360  )
361  )
362  {
363  tp->m_data = tp->ToInteger (unit);
364  }
365  }
366 
367  NS_LOG_LOGIC ("logged " << g_markingTimes->size () << " Time objects.");
368 
369  // Body of ClearMarkedTimes
370  // Assert above already guarantees g_markingTimes != 0
371  NS_LOG_LOGIC ("clearing MarkedTimes");
372  g_markingTimes->erase (g_markingTimes->begin(), g_markingTimes->end ());
373  g_markingTimes = 0;
374 
375 } // Time::ConvertTimes ()
376 
377 
378 // static
379 enum Time::Unit
381 {
382  // No function log b/c it interferes with operator<<
383  return PeekResolution ()->unit;
384 }
385 
386 
388 Time::As (const enum Unit unit) const
389 {
390  return TimeWithUnit (*this, unit);
391 }
392 
393 
394 std::ostream &
395 operator << (std::ostream & os, const Time & time)
396 {
397  os << time.As (Time::GetResolution ());
398  return os;
399 }
400 
401 
402 std::ostream &
403 operator << (std::ostream & os, const TimeWithUnit & timeU)
404 {
405  std::string unit;
406 
407  switch (timeU.m_unit)
408  {
409  case Time::Y: unit = "y"; break;
410  case Time::D: unit = "d"; break;
411  case Time::H: unit = "h"; break;
412  case Time::MIN: unit = "min"; break;
413  case Time::S: unit = "s"; break;
414  case Time::MS: unit = "ms"; break;
415  case Time::US: unit = "us"; break;
416  case Time::NS: unit = "ns"; break;
417  case Time::PS: unit = "ps"; break;
418  case Time::FS: unit = "fs"; break;
419 
420  case Time::LAST:
421  default:
422  NS_ABORT_MSG ("can't be reached");
423  unit = "unreachable";
424  break;
425  }
426 
427  int64x64_t v = timeU.m_time.To (timeU.m_unit);
428  os << v << unit;
429 
430  return os;
431 }
432 
433 
434 std::istream &
435 operator >> (std::istream & is, Time & time)
436 {
437  std::string value;
438  is >> value;
439  time = Time (value);
440  return is;
441 }
442 
444 
447 {
448  NS_LOG_FUNCTION (min << max);
449 
450  struct Checker : public AttributeChecker
451  {
452  Checker (const Time minValue, const Time maxValue)
453  : m_minValue (minValue),
454  m_maxValue (maxValue) {}
455  virtual bool Check (const AttributeValue &value) const {
456  NS_LOG_FUNCTION (&value);
457  const TimeValue *v = dynamic_cast<const TimeValue *> (&value);
458  if (v == 0)
459  {
460  return false;
461  }
462  return v->Get () >= m_minValue && v->Get () <= m_maxValue;
463  }
464  virtual std::string GetValueTypeName (void) const {
466  return "ns3::TimeValue";
467  }
468  virtual bool HasUnderlyingTypeInformation (void) const {
470  return true;
471  }
472  virtual std::string GetUnderlyingTypeInformation (void) const {
474  std::ostringstream oss;
475  oss << "Time" << " " << m_minValue << ":" << m_maxValue;
476  return oss.str ();
477  }
478  virtual Ptr<AttributeValue> Create (void) const {
480  return ns3::Create<TimeValue> ();
481  }
482  virtual bool Copy (const AttributeValue &source, AttributeValue &destination) const {
483  NS_LOG_FUNCTION (&source << &destination);
484  const TimeValue *src = dynamic_cast<const TimeValue *> (&source);
485  TimeValue *dst = dynamic_cast<TimeValue *> (&destination);
486  if (src == 0 || dst == 0)
487  {
488  return false;
489  }
490  *dst = *src;
491  return true;
492  }
493  Time m_minValue;
494  Time m_maxValue;
495  } *checker = new Checker (min, max);
496  return Ptr<const AttributeChecker> (checker, false);
497 }
498 
499 
500 } // namespace ns3
501 
static struct Resolution * PeekResolution(void)
Get the current Resolution.
Definition: nstime.h:577
std::istream & operator>>(std::istream &is, Angles &a)
initialize a struct Angles from input
Definition: angles.cc:48
nanosecond
Definition: nstime.h:117
Represent the type of an attribute.
Definition: attribute.h:166
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:102
Smart pointer class similar to boost::intrusive_ptr.
Definition: ptr.h:73
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by "...
microsecond
Definition: nstime.h:116
#define NS_ABORT_MSG(msg)
Unconditional abnormal program termination with a message.
Definition: abort.h:50
NS_ASSERT_MSG(false, "Ipv4AddressGenerator::MaskToIndex(): Impossible")
int64x64_t timeFrom
Multiplier to convert from this unit.
Definition: nstime.h:563
A Time with attached unit, to facilitate output in that unit.
Definition: nstime.h:1119
#define min(a, b)
Definition: 80211b.c:42
int64_t ToInteger(enum Unit unit) const
Get the Time value expressed in a particular unit.
Definition: nstime.h:491
Hold a value for an Attribute.
Definition: attribute.h:68
day, 24 hours
Definition: nstime.h:111
High precision numerical type, implementing Q64.64 fixed precision.
Definition: int64x64-128.h:45
minute, 60 seconds
Definition: nstime.h:113
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:67
void(* Time)(Time oldValue, Time newValue)
TracedValue callback signature for Time.
Definition: nstime.h:740
#define NS_LOG_FUNCTION_NOARGS()
Output the name of the function.
hour, 60 minutes
Definition: nstime.h:112
TimeWithUnit As(const enum Unit unit) const
Attach a unit to a Time, to facilitate output in a specific unit.
Definition: time.cc:388
Ptr< const AttributeChecker > MakeTimeChecker(const Time min, const Time max)
Helper to make a Time checker with bounded range.
Definition: time.cc:446
struct Information info[LAST]
Conversion info from current unit.
Definition: nstime.h:568
#define ATTRIBUTE_VALUE_IMPLEMENT(type)
Define the class methods belonging to attribute value class typeValue for class type.
System-independent mutex primitive, ns3::SystemMutex, and ns3::CriticalSection.
picosecond
Definition: nstime.h:118
year, 365 days
Definition: nstime.h:110
#define max(a, b)
Definition: 80211b.c:43
static enum Unit GetResolution(void)
Definition: time.cc:380
AttributeValue implementation for Time.
Definition: nstime.h:1076
Current time unit, and conversion info.
Definition: nstime.h:566
static bool StaticInit()
Function to force static initialization of Time.
Definition: time.cc:63
A class which provides a simple way to implement a Critical Section.
Definition: system-mutex.h:118
bool fromMul
Multiple when converting From, otherwise divide.
Definition: nstime.h:560
Unit
The unit to use to interpret a number representing time.
Definition: nstime.h:108
static void ConvertTimes(const enum Unit unit)
Convert existing Times to the new unit.
Definition: time.cc:343
#define NS_LOG_COMPONENT_DEFINE_MASK(name, mask)
Define a logging component with a mask.
Definition: log.h:213
Declaration of classes ns3::Time and ns3::TimeWithUnit, and the TimeValue implementation classes...
int64_t factor
Ratio of this unit / current unit.
Definition: nstime.h:561
std::ostream & operator<<(std::ostream &os, const Angles &a)
print a struct Angles to output
Definition: angles.cc:42
SystemMutex & GetMarkingMutex()
Definition: time.cc:54
Prefix all trace prints with simulation time.
Definition: log.h:116
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< T > Create(void)
Create class instances by constructors with varying numbers of arguments and return them by Ptr...
Definition: ptr.h:516
Time()
Default constructor, with value 0.
Definition: nstime.h:134
A class which provides a relatively platform-independent Mutual Exclusion thread synchronization prim...
Definition: system-mutex.h:58
NS_LOG_LOGIC("Net device "<< nd<< " is not bridged")
static Time FromDouble(double value, enum Unit unit)
Create a Time equal to value in unit unit.
Definition: nstime.h:456
static void Mark(Time *const time)
Record a Time instance with the MarkedTimes.
Definition: time.cc:287
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
Definition: log.h:262
Time Get(void) const
Definition: time.cc:443
How to convert between other units and the current unit.
Definition: nstime.h:557
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition: log.h:270
enum Time::Unit unit
Current time unit.
Definition: nstime.h:569
Time::Unit m_unit
The unit to use in output.
Definition: nstime.h:1135
static void SetResolution(enum Unit resolution)
Definition: time.cc:180
int64x64_t To(enum Unit unit) const
Get the Time value expressed in a particular unit.
Definition: nstime.h:509
static void Clear(Time *const time)
Remove a Time instance from the MarkedTimes, called by ~Time().
Definition: time.cc:313
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition: log.h:254
second
Definition: nstime.h:114
std::set< Time *> MarkedTimes
Record all instances of Time, so we can rescale them when the resolution changes. ...
Definition: nstime.h:628
static MarkedTimes * g_markingTimes
Record of outstanding Time objects which will need conversion when the resolution is set...
Definition: nstime.h:643
static void ClearMarkedTimes()
Remove all MarkedTimes.
Definition: time.cc:256
Debug message logging.
femtosecond
Definition: nstime.h:119
millisecond
Definition: nstime.h:115
Ptr< T > Copy(Ptr< T > object)
Return a deep copy of a Ptr.
Definition: ptr.h:688
Time m_time
The time.
Definition: nstime.h:1131
int64x64_t timeTo
Multiplier to convert to this unit.
Definition: nstime.h:562
int64_t m_data
Virtual time value, in the current unit.
Definition: nstime.h:728
bool toMul
Multiply when converting To, otherwise divide.
Definition: nstime.h:559
NS_ABORT_x macro definitions.