It has been noticed on several occasions that DayOfWeek function is rather slow when applied to a large list of dates, e.g. in this recent question. What faster alternatives do we have in such situations?
|
|
|||||||||
|
|
Just a literal implementation of a formula for the day of the week:
Seems to give a 5-fold speed increase:
Addition Your function is readily compilable:
|
|||||||||||||||
|
|
I will provide one solution which will be using Java and a simple Java reloader I recently introduced. This solution brings to the table up to 100-fold speed-up for large lists of dates. PreparationI will borrow @Mike's functions to generate a random list of dates, from his code in his recent question
Implementation
The input is a nested list of the type we construct randomly, which is a natural date format as it appears in Mathematica. I subtract 1 from month, to comply with the Java conventions. Use and benchmarks
There is a 100-fold speedup for this example. Note that there is a small constant overhead of calling Java, so the larger is your list of dates, the more you gain. RemarksI think that this can be one of the "canonical" examples of a situation where the use of Java is more than appropriate. Generally, this happens when some of the following is true:
Effective use of Java / JLink implies that loops are outsourced to Java. Only then the overhead of Java / JLink will not play a big role. Performing looping in Mathematica while invoking Java functions is likely to not be faster, and often be slower, than doing it all in Mathematica. A big thanks goes to @Mike for spotting a bug in the reloader (which has been now fixed). |
||||
|
|
|
I've shown off Larsen's method before (and see this as well), but here it is as a formal answer:
This assumes the use of the Gregorian system, so this will require some modification if you need to work with dates older than the switching date September 14, 1752 (where the Julian system was still in use). Here's how to adapt
|
|||||
|
|
This recent post reminded me that Using the
~ 41X speed-up. |
|||
|
|
Super-fast. You need the Joda Time library for that. If you're a hardcore JLink user, you have the first two lines in your init.m anyway, so the problem reduces to 71 characters, with an amazing speed. Joda Time is ISO 8601-compliant. |
|||||||||||
|
|
I will provide one solution which will be using ANSI C and LibraryLink. Needless to say that this is a speeder...(Platform: MacOSX, gcc 4.2) The preparations are the same as in Leonid's answer. Implementation
Create the Library and load it
Microsoft's compiler (CL) has similar options with just different naming... The dayOfWeek function
Timing
Conclusion As the argumentation holds to use Java, because of it's simple interface I think I've shown that this holds as well for C/C++ and is unbeatable fast. |
|||||||||||||||||
|




