The Darkness Behind DateTime.Now
Join the DZone community and get the full member experience.
Join For Freea short while ago david penton and peter bromberg had a conversation on twitter about performance differences between using datetime.now and datetime.utcnow properties and the best practices related to them. i jumped in their discussion with my thoughts and peter did a nice job by putting a summary on eggheadcafe . while that summary suffices for many developers to understand the problems associated with wrong usage of datetime.now (which is very commonplace), i thought that it may be a good idea to dedicate a blog post to this topic with more details for two reasons: first, we need to repeat certain stuff to spread the word about a good or bad practice and inform developers about it, and second, it may be worth seeing the reasons, numbers, and performance measurements for everyone to understand the points.
in this post i’m going to discuss the applications of two properties of datetime structure, now and utcnow , as well as stopwatch class, and provide a set of measurements of performance impacts associated with each one.
datetime.now
a very commonly-used and well-known property of the datetime structure in .net is now which simply returns the current date and time on the machine executing the code. such a property is provided in almost all programming languages as a built-in feature and has many applications. unfortunately, most of the .net developers have been misusing this property for years for purposes other than what it’s supposed to serve for. i can outline two possible reasons for this problem:
- most of the developers are careless about all the properties and methods provided by built-in types in a language, so they don’t discover all the details about them. in fact, they use something that just solves their problem regardless of the side-effects.
- the traditional use of similar methods in languages used by .net developers in the past has left some bad habits for them while the internal working of this property is slightly different from what is available in some other languages.
i have to admit that i was a developer who used to apply this property for wrong purposes in the early years of my .net development, and may still misuse that for simple codes where i don’t care much about performance, but it’s not something to use in each and every situation.
to clarify the use of the now property of datetime structure i have to state that this property is not designed to be used in cases such as when you want to retrieve the time for internal calculations in your program, store a datetime value in database, or calculate the runtime performance of a piece of code. in contrast, it is designed to be used when you want to display the current date and time on a machine to your users or store such a value in local log files where you want the local time to be used.
although it’s hard to give a general guideline on good and bad uses of this property, i guess that the abovementioned examples can give you enough hints on when and where to use this property. a good question that you may ask about this property is why we distinguish these cases and consider some uses as bad practices. the answer is laid in the internal implementation of the now property.
public static datetime now { get { datetime utcnow = datetime.utcnow; bool isambiguousdst = false; long ticks = timezoneinfo.getdatetimenowutcoffsetfromutc(utcnow, out isambiguousdst).ticks; long num = utcnow.ticks + ticks; if (num > 3155378975999999999l) { return new datetime(3155378975999999999l, datetimekind.local); } if (num < 0l) { return new datetime(0l, datetimekind.local); } return new datetime(num, datetimekind.local, isambiguousdst); } }
essentially, this property is converting the current date and time in utc to the local values and has an extra processing associated with this which is the source of the overhead that i will discuss later.
datetime.utcnow
another commonly-used property of datetime is utcnow even though it’s not used as commonly as the now property. this property returns the current date and time in utc. this property is designed to serve for many places where now is being misused and i listed some of the highlights in the previous section.
in general, if you’re going to store datetime values in database or perform calculations on such values, it’s better to use utcnow because in the former case, this helps you have a universal value regardless of the local time of the machine where you host your program and in the latter case there is no difference between the duration of time calculated by now and utcnow .
as you can see below, utcnow has a simpler implementation than now and in fact, now is written based on utcnow with some additions.
public static datetime utcnow { [targetedpatchingoptout("performance critical to inline across ngen image boundaries"), securitysafecritical] get { long systemtimeasfiletime = datetime.getsystemtimeasfiletime(); return new datetime((ulong)(systemtimeasfiletime + 504911232000000000l | 4611686018427387904l)); } }
stopwatch
a lesser-used aspect of datetime calculations in .net is stopwatch type that is designed to assist programmers to calculate the runtime performance of a piece of code. most programmers tend to use datetime.now and datetime.utcnow before and after a piece of code to find the duration of time that it takes to execute.
stopwatch relies on a public static method called gettimestamp which works in two modes. if it’s not used in high resolution mode, it applies datetime.utcnow , otherwise it applies queryperformancecounter from windows api that i will discuss in the next section.
public static long gettimestamp() { if (stopwatch.ishighresolution) { long result = 0l; safenativemethods.queryperformancecounter(out result); return result; } return datetime.utcnow.ticks; }
queryperformancecounter
while this is something that a .net developer doesn’t need to use and care about, i have to point out that queryperformancecounter is a windows api method that is used by some built-in .net types behind the scenes. this is considered an outdated approach in .net development and you need to use interoperability apis to have access to this function which provides access to a high-resolution performance counter.
[dllimport("kernel32.dll")] public static extern void queryperformancecounter(ref long ticks);
in the next section i apply this method to compute the time taken to execute my benchmarks and the main reason is that i want to have a higher precision, so using a more fundamental operating system function can help.
comparison
nothing is better than seeing some numbers reflecting the points mentioned above, so here i try to write simple programs that compare the performance of datetime.now , datetime.utcnow , and stopwatch . normally, it’s hard to compare the properties of datetime structure with stopwatch as they are different by nature, however, thinking a little bit about good examples, it’s possible to relate them together and compare their runtime performance.
here i develop three pieces of code that accomplish the same goal using these three approaches. i generate different sample sizes (incremented by a unit of 500 for 10 sample data batches) and perform a very basic (and senseless) task. i use datetime.now , datetime.utcnow , and stopwatch to calculate the time that it takes to run my code. i measure my elapsed time using queryperformancecounter to have a good precision.
the first code is for datetime.now .
private static void testdatetimenow() { console.writeline("testing datetime.now ..."); for (int samplesize = 500; samplesize <= 5000; samplesize += 500) { long start = 0; queryperformancecounter(ref start); for (int counter = 0; counter < samplesize; counter++) { datetime starttime = datetime.now; int dumbsum = 0; for (int temp = 0; temp < 5; temp++) dumbsum++; datetime endtime = datetime.now; timespan duration = endtime - starttime; } long end = 0; queryperformancecounter(ref end); long time = 0; time = end - start; console.writeline("sample size: {0} - time: {1}", samplesize, time); } }
a very similar code can be used with datetime.utcnow .
private static void testdatetimenow() { console.writeline("testing datetime.utcnow ..."); for (int samplesize = 500; samplesize <= 5000; samplesize += 500) { long start = 0; queryperformancecounter(ref start); for (int counter = 0; counter < samplesize; counter++) { datetime starttime = datetime.utcnow; int dumbsum = 0; for (int temp = 0; temp < 5; temp++) dumbsum++; datetime endtime = datetime.utcnow; timespan duration = endtime - starttime; } long end = 0; queryperformancecounter(ref end); long time = 0; time = end - start; console.writeline("sample size: {0} - time: {1}", samplesize, time); } }
and finally, stopwatch can be applied to measure the duration of time to execute this code using its start and stop methods as well as its elapsed property.
private static void teststopwatch() { console.writeline("testing stopwatch ..."); for (int samplesize = 500; samplesize <= 5000; samplesize += 500) { long start = 0; queryperformancecounter(ref start); for (int counter = 0; counter < samplesize; counter++) { stopwatch watch = new stopwatch(); watch.start(); int dumbsum = 0; for (int temp = 0; temp < 5; temp++) dumbsum++; watch.stop(); timespan duration = watch.elapsed; } long end = 0; queryperformancecounter(ref end); long time = 0; time = end - start; console.writeline("sample size: {0} - time: {1}", samplesize, time); } }
sometimes a picture is worth a thousand words and the below diagram can reflect whatever i’ve mentioned so far.
here we see some interesting results and it’s more interesting when we consider the fact that these codes are tested with realistic sample data sizes between 500 to 5000. here datetime.now (the blue line) has the worst performance at top followed by stopwatch (the green line) and datetime.utcnow (the red line). utcnow stands much lower than the other options with a very steady pace (unlike other two options) and surprisingly, performs better than stopwatch . this is of course expected as i showed you the internal implementation of stopwatch which is using datetime.utcnow with some extra processing.
here a good question is why we need to use stopwatch when datetime.utcnow is performing better. the answer is that it’s possible to do that and actually, it’s much better if you’re sure that you get such a significant difference by applying utcnow rather than stopwatch . but there is a major and a minor advantage for stopwatch over utcnow . the major advantage is that stopwatch can perform in a higher resolution by applying queryperformancecounter rather than datetime.utcnow . the minor advantage is that stopwatch provides a more fluent and human-readable method to perform this task.
summary
many .net developers misuse the properties of datetime structure and apply now for purposes where it’s not designed for which reduces the performance of the code. utcnow is what should be used for many cases rather than now , and even for timing measurements there is a particular class called stopwatch .
seeing a quantitative comparison between these approaches visualized in a simple diagram, you can understand why it’s recommended to use each property or type in its own place. i am very sure that the misuse of these options in the .net codes written in the past decade has had a major impact on many .net applications and it’s sad to say this because despite a decade of existence and six major releases of the .net framework with a lot of investments in training and documentation, there hasn’t been a good focus on the underlying infrastructure of the framework and such important practices.
i’ve uploaded the sample code for this post that you can run on your machine to compare these three approaches yourself.
Published at DZone with permission of Keyvan Nayyeri. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments