Is there a non-allocating way to get the difference between two LocalDateTime points? - nodatime

I do appreciate why differences between two LocalDateTime instance are expressed as Periods and not Durations, but I could not find a reason why Period is a class and not a struct.
I am helping to port a codebase that did lots of this:
DateTime t1;
DateTime t2;
TimeSpan diff = t2-t1;
// After port, with a surprising allocation
LocalDateTime t1;
LocalDateTime t2;
Period diff = t2-t1;
It seems like a bit of a perf/GC pitfall, and I'm just curious why Period is a class and not a struct?

The main reason for Period to be a class is that it would be huge - it has 6 long fields and 4 int fields. That would be 64 bytes - an awful lot to pass as a method argument etc. While some other structs in Noda Time are "pretty big" they're not that big.
But it's worth noting that the two pieces of code do radically different things. The Noda Time equivalent of TimeSpan isn't Period; it's Duration, which is a struct. If you don't need a calendrical calculation, you might want to consider converting your two LocalDateTime values to Instant values in UTC (or avoid using LocalDateTime to start with), and then take the difference between those two instants.
Internally, there are non-allocating ways of getting "the number of days" between dates, for example... we could potentially expose something like that publicly, but I think it would be worth doing benchmarking first to prove this is really important. (The GC is pretty good at collecting very-temporary objects. Sure, it's not free - but I think code would have to be doing very little other than this for it to become a major factor.)

Related

Representing timestamps

I would like to represent the timestamp coming from an HTMLMediaElement. Its defining characteristics are:
Its value is represented as a Double
It can be queried at any time using getCurrentTime :: IO Double (as partially applied on a given HTMLMediaElement)
It is potentially continuously changing (whenever the media player is playing)
My initial plan was to represent it as a Behavior t Double that re-runs the IO Double every time it is observed, but that hasn't worked out too well.
Things I've tried:
Using a Behavior that is prodded under the hood at a fixed frequency, as described in the workaround section of this question
Passing an Event t () representing the desired sampling frequency, and returning an Event t Double that holds the coinciding timestamps
I don't really like either -- the first one either couples the behaviour (sorry) too much to my specific use case (if I use the eventual sampling frequency I'll use in my app) or seems wasteful (if I use something like 1 kHz sampling when creating the Behavior just to then sample it at 60 Hz on the application end), and the second is quite inflexible if you want to do more than one thing with the timestamp at different sampling rates.
Right now, using an Event to explicitly sample the time (your second option) value is your best bet. We haven't yet created a way to write Behaviors that lazily poll outside resources, although that is something that I hope we'll be able to get done soon.
Keep in mind that, with your second option, you don't necessarily need to use a specific sampling rate; instead, you can sample on-demand, and even have multiple locations doing that sampling. It's not perfect, but I hope that'll let you get the job done!

How to convert epoch time (unix timestamp) in D to standard (year-month-day)

How do you convert epoch time (unix timestamp) to standard time in D? Is there a way to customize the format?
You really should separate questions out, not ask two completely different questions at the same time.
How do you convert epoch time (unix timestamp) to standard time in D?
If you need to convert from unix time to SysTime's "std time," then you use unixTimeToStdTime:
assert(unixTimeToStdTime(0) == (Date(1970, 1, 1) - Date.init).total!"hnsecs");
So, if you do SysTime(unixTimeToStdTime(0)), you'll get a SysTime in your local time zone at the point in time when it was midnight, January 1st 1970 in UTC (i.e. the epoch time). Unlike the other SysTime constructors, it does not treat the time it's given as being in the timezone that it's given. Rather, it just sets its stdTime to the given value, and it's timezone to the given value. So, to construct an identical SysTime with the other constructors, you'd do something like
auto epochInLocalTime = SysTime(Date(1970, 1, 1), UTC()).toLocalTime();
If you want to convert in the opposite direction, stdTimeToUnixTime will convert a std time to a unix time. However, SysTime has toUnixTime on it, making it so that you generally don't need stdTimeToUnixTime.
time_t epoch = epochInLocalTime.toUnixTime();
However, one thing to be aware of is the fact that std.datetime truly deals with unix time - time_t is always considered to be in UTC. The reason that this matters is that for some inexplicable reason, Windows applies the local time's DST to time_t so that the UTC offset never changes, which means that it's wrong for a good chunk of the year. It works with all of the Microsoft's functions which use time_t, because they expect that nonsense, but you'll have interoperability problems if you try and use a Windows time_t with another box or with a library like std.datetime which actually uses time_t correctly.
Is there a way to customize the format?
You mean that you're looking for a way to provide a user-defined format for a string representing the time (like C's strftime)? std.datetime doesn't have that yet. The API still needs to be designed for it. Some discussion has taken place, but it hasn't been settled on yet. So, it'll happen eventually, but it could be a while.
In the interim, you have toISOString, toISOExtString, and toSimpleString, which use the ISO format, the ISO extended format, and Boost's simple string format respectively. In general, I'd suggest using toISOExtString, because it's both easily read by humans and standard. It's also generally best to put it in UTC (e.g. sysTime.toUTC()) when communicating with other computers (as opposed to printing it out for humans), because then the time zone is part of it, unlike with LocalTime, which doesn't append the time zone.
If you haven't read this article on std.datetime yet, then I suggest that you do, since it should give you a good overview of the module and how to use it.
I'm not familiar with D, but according to std.datetime, you could use these steps
long unixTimeToStdTime(time_t)
struct SysTime(long stdTime)
SysTime.dayOfGregorianCal()
struct Date(int day)
Date.toISOExtString()

Is there a Haskell Time Typeclass

I want to build a function with type signature Time t => t -> Bool. When looking at the documentation of Data.Time there are several different types that work on time, such as: UTCTime, LocalTime, and ZonedTime, but I find no typeclass that unifies them. Is there any such one or should I treat time just as a Num? (i.e. a continuum)
The vector-space package has a affine space typeclass.
Diff p is here the time duration type (which should be an instance of VectorSpace), and p is the time point type. You'll need an extra Ord instance for comparisons.
This provides you with linear interpolation between time points for free.
There is no such type class in the standard time library, but it is possible to implement one by yourself.
However, usually you should construct your program logic in such a way that UTCTime is used for all time-based calculations (and this is not Haskell-specific). LocalTime and ZonedTime should just be used to convert back and forth between UTC and a presentation that is showed to the user or for data that comes from external sources. This is probably the reason there are no ready-made functions for calculating time-diffs and time additions for local and zoned time types.
Time is slightly strange.
Time can refer to a specific instant in time (e.g., 09:27 AM, 14 Feb 1821 AD), or a duration of time (e.g., 6 minutes).
It makes sense to add and subtract durations. It doesn't really make sense to find the sum of two instants in time; what would this represent? Adding a duration to an instant would give you another instant; that makes sense. And subtracting one instance from another ought to give you the duration between them.
In summary, temporal arithmetic is not as simple as you might imagine.
Now, what the time package provides? I have no idea. It sounds like all the times you mentioned are instants in time, not time durations...
Take a look at the HasTime class in the time-lens package.
It gives you (both read and write) access to the TimeOfDay component of all those structures. So, if you implement your function for TimeOfDay, it can be easily generalised to LocalTime, ZonedTime and UTCTime.
According to the documentation (http://www.haskell.org/ghc/docs/7.0.2/html/libraries/time-1.2.0.3/Data-Time-Format.html), all of UTCTime, ZonedTime and LocalTime are instances of the typeclasses FormatTime and ParseTime. They should be what you are looking for.

Naming suggestion for a class containing a timestamp and a float value?

I need to name this structure:
struct NameNeeded
{
DateTime timestamp;
float value;
}
I will have arrays of this struct (a time-series).
I'd like a short and suggestive name. The data is financial (and Tick is not a good name).
The best one I can think of is DataPoint, but I feel that a better one exists :)
How would you name it?
Since you have a data value and an associated timestamp, the first thing that popped into my head was DataSample. I pictured a series of these, as if you were taking a digital sampling of an analog signal (the two values were like x- and y-coordinates on a graph).
My old scientist neurons are telling me that this is a Measurement. A measurement is an instrument reading associated with some context - time, position, experimental conditions, and so on.
The other metaphor that springs to mind is a Snapshot, or a moment in an evolving scene illuminated by a strobe light - an Instant, perhaps.
Given that we can't associate a specific concept with the float value structure member, only vague names such as "Value", "Number", "Float" or "Data" come to mind.
The DateTime timestamp member suggests to me that the name should have a time related suffix such as "When", "AtTime", "Instant" or "Moment"
So, combining these name fragments and you could have
ValueWhen
ValueAtInstant
NumberWhen
DataAtTime
etc.
When stuck on a naming problem, consulting a dictionary or thesaurus can sometimes help. It's pleasing to see well chosen type names, and gratifying to come up with them - good luck with your quest.
I would personally include "Float" in the name, to leave open the possibility of providing other time-stamped types. For example, you could provide a timestamped int or enum for analyst recommendation.
If you want the time-stamping to be implicit, consider "FloatValue." Making it implicit might be desirable if other attributes might someday join the timestamp (e.g., source of data, confidence level, or uncertainty).
If you want to be explicit, one possibility would be "RecordedFloat."

Are there any languages that allow units?

When writing the following today in C#
DateTime.Now.AddYears(-60)
I wondered whether there are any languages that allow a more natural syntax with units:
DateTime.Now - 60years
Does anyone know of any? Specifically, I'm interested in the presence of unit operators(?) that turn "60years" into e.g. "TimeSpan.FromYears(60)". It'd also be neat to be able to define your own unit operators, similar to how you can write conversion operators in C#
(Yes, I know TimeSpan doesn't cater for years -- it's an example.)
F# has units of measure. Some examples from
http://blogs.msdn.com/andrewkennedy/archive/2008/08/20/units-of-measure-in-f-part-one-introducing-units.aspx
You might be interested in F# Units of Measure support
Well the ActiveSupport library for ruby extends the Integer class with methods like hours and days which allows you to write things like:
Time.now + 5.days
But that's not really a syntax feature - it's just a method call and is possible in any language that allows you to add methods to an existing class. You could do it in C# with extension methods - though it would have to be 5.days() there.
There is a Boost C++ library for Units that makes extensive use of template metaprogramming to provide something similar to the syntax you desire.
quantity<force> F(2.0*newton);
quantity<length> dx(2.0*meter);
quantity<energy> E(work(F,dx));
http://www.boost.org/doc/libs/1_37_0/doc/html/boost_units.html
Sun's new language Fortress supports units and, if memory serves, is smart enough to stop you doing odd things such as subtracting measures of time from measures of length.
And Mathematica has units of measure and a not-too-unwieldy syntax for handling them.
Unum does pretty much exactly that for Python, allowing code like:
>>> TON + 500*KG
1.5 [t]
>>> 5E-8*M - 28*ANGSTROM
472.0 [angstrom]
>>> 3*H + 20*MIN + 15*S
3.3375 [h]
>>> H == 60*MIN
True
>>> 10000*S > 3*H + 15*MIN
False
>>>
Ada and its cousin, VHDL, directly support the concept of units. Since these languages are extremely strongly typed, units are a natural ability of the strictness of types.
See the answer on C# Extensions where the int class is extended to support methods such as Hours(), Days(), etc.
Powershell has the kB, MB, and GB operators for handling file sizes etc.
The DATE_ADD() function in MSSQL accepts units such as day, hour etc for date arithmetic.
Java's JODA library works that way.
And there's JSR-275 that proposes a units framework.
I first heard about this issue back in 1997 from Martin Fowler. He wrote about it in his "Analysis Patterns".
Not units, per se... but one way to use extension methods to give you unit-like functionality. This example is for TimeSpan, specifically.
static class TimeExtensions
{
public static TimeSpan ToDays(this int i)
{
return new TimeSpan(i, 0, 0, 0, 0);
}
public static TimeSpan ToHours(this int i)
{
return new TimeSpan(0, i, 0, 0, 0);
}
public static TimeSpan ToMinutes(this int i)
{
return new TimeSpan(0, 0, i, 0, 0);
}
public static TimeSpan ToSeconds(this int i)
{
return new TimeSpan(0, 0, 0, i, 0);
}
public static TimeSpan ToMilliseconds(this int i)
{
return new TimeSpan(0, 0, 0, 0, i);
}
}
Then, simply 4.ToMinutes() gives you a TimeSpan of 4 minutes. If you have similar base classes to work with to represent other unit types, the same sort of extension functionality can be added.
(Note: this is merely a C# representation of the Ruby example.)
When you use units, you're actually assigning a type. The conversions could be implemented through casting, or through differentiating function calls based on parameter types (function overloading). Just about any statically typed language (that allows you to define types thoroughly) would allow you to do something similar. It would make your program more robust, though those who prefer dynamically typed languages may argue that gains are small relative to time spent implementing such a thorough type system for most applications. Building a Mars Climate Orbiter would, on the other hand, merit such a type system.
The syntax is a little different, but your example strikes me as very similar to common examples of how some would use Haskell's type system (or that of any typed functional language), though, as I mentioned, this is also doable in C-like languages as well.
I gues C++ , you can make unit class with overloaded operators and some #define macros
I don't know if one exists yet, but I would expect to start seeing such things popping up as DSLs in the next couple of years. I'm thinking sort of like a next generation MATLAB or something. I'm sure there are loads of mathematical, scientific, and engineering uses for such things.
MySQL has this feature
mysql> SELECT '2008-12-31 23:59:59' + INTERVAL 1 SECOND;
-> '2009-01-01 00:00:00'
mysql> SELECT INTERVAL 1 DAY + '2008-12-31';
-> '2009-01-01'
mysql> SELECT '2005-01-01' - INTERVAL 1 SECOND;
-> '2004-12-31 23:59:59'
SQL, or atleast MySQL has some basic time based unit support.
mysql> SELECT DATE_SUB(NOW(), INTERVAL 1 DAY) AS `yesterday`, NOW() + INTERVAL 1 DAY AS `tomorrow`;
+---------------------+---------------------+
| yesterday | tomorrow |
+---------------------+---------------------+
| 2009-08-20 06:55:05 | 2009-08-22 06:55:05 |
+---------------------+---------------------+
1 row in set (0.00 sec)
I know what you mean, and I too have been curious about this. (My high school chemistry teacher was adamant that numbers without units were fairly meaningless. Anyway...)
With any strongly typed language, you can write classes for these concepts. I've written them in C++, Java and Pascal. Google "Units" and "Java" and you can find a library that has all sorts of physical measurements encapsulated like this.
C++, with it's slicker type conversions and operator overloading can make this look more natural. You can actually make things pretty slick, getting at what I think you want. Java, although it does this, will require more explicit conversions and awkward syntax.
But no, I haven't seen it.
Look for domain specific languages created for scientists, even "educational" ones.
Frink is a language purpose-built for "physical calculations" like that. From the documentation:
Frink is a practical calculating tool
and programming language designed to
make physical calculations simple, to
help ensure that answers come out
right [..]. It tracks units of measure
(feet, meters, kilograms, watts, etc.)
through all calculations, allowing you
to mix units of measure transparently
[..]
Your example in Frink:
now[] - 60 years
I have not seen such a language that supports it inherently. However you could certainly write your own Date based objects in a variety of languages, if your so inclined.
I'm sure it's not what you're looking for, but in the area of test and measurement equipment, it would not be unusual for a 'test program' to include statements which operate on values expressed with voltage, current or time units.
Very specialised stuff, though, and barely recognisable by most as programming languages.
PHP's strtotime() function does it very nicely. It takes a string and an optional time as parameters and will parse the string to figure out a new time.
Examples:
$newTime = strtotime('last monday');
$newTime = strtotime('- 2 days', $originalTime);
$newTime = strtotime('- 60 years', $originalTime);
$newTime = strtotime('+ 1 week 1 day', $originalTime);
More here: http://us2.php.net/strtotime
Not part of the language, but I've seen that done before in C, something like:
#define NOW time(0)
#define PLUS +
#define AND +
#define MINUS -
#define SECOND * 1
#define SECONDS * 1
#define MINUTE * 60
#define MINUTES * 60
#define HOUR * 3600
#define HOURS * 3600
#define DAY * 86400
#define DAYS * 86400
time_t waitUntil = NOW PLUS 1 HOUR AND 23 MINUTES;
It seemed like an abomination to me at the time, in the same class as "#define begin {" and "#define end }" - if you don't like the way the language works, use a different language; don't try to bend it to your will in such a hideous way.
It still seems like an abomination, but I've mellowed in my old age and can at least understand why maybe someone thought it was a good idea.
PowerShell has some basic support. For instance 5GB/1MB evaluates to 5120
Syntacticly, I'm not really sure what the benifit would be of
DateTime.Now + 60 years
Over
DateTime.Now.AddYears (60)
My typical method for dealing with "units" is to define constants that convert those units into the data object's base unit if multiplied. Since someone (breifly) tagged this with Ada, the Ada version would be:
Years : constant := 60.0 * 60.0 * 24.0 * 365.0;
DateTime.Now := DateTime.Now + (60.0 * Years);
I think you can do pretty much the same think in C++, except that their time objects are liable to be large integers instead of reals.
In Perl, you can use DateTime which allows such things as:
my $dt = DateTime->now
$dt->subtract( hours => 1 );

Resources