Three ways to count time in AX 2012

Continue reading

Today I would like to show you three useful approaches to count elapsed time, inside the Dynamics AX 2012. I will also perform simple comparison between the methods.

First method useful and widely used in the community is to use Global class method timeConsumed.

timeConsumed takes two arguments of int type and returns string in format X hours X minutes X seconds. It is particularly useful because we do not have to bother to format string it does it for us. One remark is that this method will return time over 24 hour intervals.

static void timeConsumedFcn(Args _args)

{

   FromTime    startTime;

   int seconds = 5;

   int     i;

   str   elapsed;

   ;

   startTime = timeNow();

   i = sleep(seconds*1000);  

   elapsed = timeConsumed(startTime, timeNow());

   info(strFmt("Time elapsed: %1", elapsed));

}

Another approach is to use WinApi class static method called getTickCount. It gives us greater precision than previous approach so that we can measure to milliseconds accuracy.  Worth thing to notice here is that this method comes in two flavours, first is getTickCount which returns int and also getTickCount64 which returns int64 as we will see in the comparison below this gives us greater accuracy.

static void winApiTickCount(Args _args)

{

   int64    startTime, endTime;

   int seconds = 5;

   int     i;

   int64   elapsed;

   ;

   startTime = WinAPI::getTickCount64();

   i = sleep(seconds*1000);  

   endTime = WinAPI::getTickCount64();

   elapsed = endTime - startTime;

   info(strFmt("Time elapsed: %1", elapsed));

}

The third way is to use .Net class called Stopwatch. Dynamics AX 2012 has a feature called .Net interop which allows us to access assemblies installed with .Net framework, through X++. This can be very useful, you can read more about this on msdn.

static void stopWatchdotNetInterop(Args _args)

{

   System.Diagnostics.Stopwatch  stopwatch = new System.Diagnostics.Stopwatch();

   int seconds = 5;

   int     i;

   int64   elapsed;

   ;

   stopwatch.Start();

   i = sleep(seconds*1000);  

   stopwatch.Stop();

   elapsed = stopwatch.get_ElapsedMilliseconds();

   info(strFmt("Time elapsed: %1", elapsed));

}

Conclusion:

By looking at the distance of mean value from the real value in our case 5s we can see that indeed winApi64(getTickCount64) is slightly more accurate than winApi(getTickCount), and stopwatch is even more accurate than winApi64.

For most of the cases WinAPI::getTickCount64 is accurate enough but if we want to achieve more accuracy we should use .Net interop.

More articles
Explore our blog

What can we do for you?

We'd love to hear about your project. Our team will get back to you within two working days.

Thank you for inquiry, we’ve passed it to our sales department, our representative will reach you back in his earliest convenience.
Oops! Something went wrong while submitting the form.