Skip to content

Commit 2e6b9c8

Browse files
committed
added high precision clock and ros header timestamp using high precision clock
1 parent 4fe49cd commit 2e6b9c8

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed

Runtime/Scripts/ROS/MessageTypes/Std/ZOROSStdMessages.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,15 @@ public TimeMessage(uint secs, uint nsecs) {
2222
this.nsecs = nsecs;
2323
}
2424

25+
[Newtonsoft.Json.JsonIgnore]
26+
private ZO.Util.ZOClock _clock = new ZO.Util.ZOClock();
2527
/// <summary>
2628
/// Sets the timestamp to Now
2729
/// </summary>
2830
public void Now() {
2931
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
30-
TimeSpan timeSpan = DateTime.Now.ToUniversalTime() - epoch;
32+
// TimeSpan timeSpan = DateTime.Now.ToUniversalTime() - epoch;
33+
TimeSpan timeSpan = _clock.UtcNow - epoch;
3134
double msecs = timeSpan.TotalMilliseconds;
3235
secs = (uint)(msecs / 1000);
3336
nsecs = (uint)((msecs / 1000 - secs) * 1e+9);
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System;
2+
using System.Threading;
3+
using System.Diagnostics;
4+
5+
namespace ZO.Util {
6+
public sealed class ZOClock : IDisposable {
7+
private readonly long _maxIdleTime = TimeSpan.FromSeconds(10).Ticks;
8+
private const long TicksMultiplier = 1000 * TimeSpan.TicksPerMillisecond;
9+
10+
private readonly ThreadLocal<DateTime> _startTime =
11+
new ThreadLocal<DateTime>(() => DateTime.UtcNow, false);
12+
13+
private readonly ThreadLocal<double> _startTimestamp =
14+
new ThreadLocal<double>(() => Stopwatch.GetTimestamp(), false);
15+
16+
public DateTime UtcNow {
17+
get {
18+
double endTimestamp = Stopwatch.GetTimestamp();
19+
20+
var durationInTicks = (endTimestamp - _startTimestamp.Value) / Stopwatch.Frequency * TicksMultiplier;
21+
if (durationInTicks >= _maxIdleTime) {
22+
_startTimestamp.Value = Stopwatch.GetTimestamp();
23+
_startTime.Value = DateTime.UtcNow;
24+
return _startTime.Value;
25+
}
26+
27+
return _startTime.Value.AddTicks((long)durationInTicks);
28+
}
29+
}
30+
31+
public void Dispose() {
32+
_startTime.Dispose();
33+
_startTimestamp.Dispose();
34+
}
35+
}
36+
37+
}

Runtime/Scripts/Util/System/ZOClock.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)