Home

Monday, June 20, 2016

THREE WAYS TO COUNT TIME IN DYNAMICS AX 2012

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 returnsint64 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. Microsoft 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 (https://msdn.microsoft.com/en-us/library/cc598160.aspx).
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));
}
Simple comparison between methods, evaluated for ten repetitions of above jobs:
 winApi64winApistopwatch
Mean5.00085.00755.0001
SD0.00060.00050.0003
*in seconds, mean (arithmetic mean), SD (standard deviation)
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.

No comments:

Post a Comment