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.