tags:

views:

461

answers:

2

Hey, as of lately, I've been trying to find good ways to smoothen out thread sleeps (incase it gets disturbed or if your computer laggs etc).

So which is an overall "better performance" method?

JAVA's System.currentTimeMillis() method for C#:

public static double GetCurrentMilliseconds()
{
    DateTime staticDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan timeSpan = DateTime.UtcNow - staticDate;
    return timeSpan.TotalMilliseconds;
}

System.currentTimeMillis() in use:

    public void Run()
    {
        this.lastUpdate = TimeUtilities.GetCurrentMilliseconds();
        while (isRunning)
        {
            if (TimeUtilities.GetCurrentMilliseconds() - lastUpdate >= 600)
            {
                lastUpdate = TimeUtilities.GetCurrentMilliseconds();
                // bla bla bla...
            }

            try
            {
                Thread.Sleep(100);
            }
            catch (Exception ex)
            {
                Jolt.GetLog().WriteException(ex);
            }
        }
    }

and C#'s Environment.TickCount:

    private void Run()
    {
        double lastUpdate = Environment.TickCount;

        while (isRunning)
        {
            if (lastUpdate + 600 < Environment.TickCount)
            {
                lastUpdate = Environment.TickCount;
                // bla bla bla...
            }

            try
            {
                Thread.Sleep(100);
            }
            catch (Exception ex)
            {
                Jolt.GetLog().WriteException(ex);
            }
        }
    }

Any help would be appreciated. Otherwise if this is a bad idea, could you please provide a better way to do this.

A: 

TickCount has better performance for sure.

The overhead of calculating current time is not needed in this usecase. You only care about elapsed time so it doesn't make difference if epoch is 1970 or the start of the process.

ZZ Coder
A: 

Using the TickCount approach has better performance, for several reasons:

  • it's an integer, not a multi-byte data structure
  • it's directly available, not requiring the various computations

Performance-wise, you shouldn't use the double type. To measure a span of 100 seconds, an int should be sufficient. Notice that TickCount rolls over from positive to negative after 24 days, so using TickCount won't work after that time anymore if you use double; if you use int, you should write it as

if (Environment.TickCount-lastUpdate > 600)
Martin v. Löwis
Thanks mate, this is probably the answer i needed.
AJ Ravindiran