开发者

Faster alternative to DateTime.FromFileTime(fileTime).ToLocalTime().ToString()

开发者 https://www.devze.com 2023-03-17 03:53 出处:网络
While profiling my application I found that DateTime.FromFileTime(long fileTime) is slow. Does anyone know of a fast managed equivalent or the windows file time format?

While profiling my application I found that DateTime.FromFileTime(long fileTime) is slow.

Does anyone know of a fast managed equivalent or the windows file time format?

[EDIT] I was able to get some speed gains doing the following:

 var timeStr = FastTimeStringFormat(new DateTime(fileTime + 0x701ce1722770000L, DateTimeKind.Utc).ToLocalTime()); // + 0x701ce1722770000L is the offset needed to convert to UTC DateTime

For more speed but less safety (no intra-day daylight savings time checks), you can cache the ToLocalTime offset (long) and spare the more expensive expensive ToLocalTime() call.

On App Start:

long fileTimeOffset = DateTime.Today.Subtract(DateTime.Today.ToUniversalTime()).Ticks + 0x701ce1722770000L;

Then in your critical path:

var timeStr = FastTimeStringFormat(new DateTime(fileTime + fileTimeOffset));

As it tur开发者_如何学JAVAned out ToString is very expensive and the following is faster.

    public static unsafe string FastTimeStringFormat(DateTime time)
    {
        // modified version from the following post:
        // http://geekswithblogs.net/akraus1/archive/2006/04/23/76146.aspx
        // this one is also more accurate because of true divide by 10, beware of less accurate versions that do not use division


        char* FixedCharArray = stackalloc char[13];

        int hour = time.Hour; // Cache property values

        int minute = time.Minute;

        int second = time.Second;

        int ms = time.Millisecond;

        // hour

        FixedCharArray[0] = (Char)('0' + hour / 10);

        FixedCharArray[1] = (Char)('0' + hour % 10);

        FixedCharArray[2] = ':';
        // minute

        FixedCharArray[3] = (Char)('0' + minute / 10);

        FixedCharArray[4] = (Char)('0' + minute % 10);

        FixedCharArray[5] = ':';
        // seconds

        FixedCharArray[6] = (Char)('0' + second / 10);

        FixedCharArray[7] = (Char)('0' + second % 10);

        FixedCharArray[8] = '.';
        // miliseconds

        FixedCharArray[9] = (Char)('0' + ms / 100);

        FixedCharArray[10] = (Char)('0' + ms % 100 / 10);

        FixedCharArray[11] = (Char)('0' + ms % 10);

        return new String(FixedCharArray);

    }


DateTime.FromFileTime() is implemented in managed code, there are no P/Invoke calls involved.

The performance hit you're experiencing might come from the conversion to local time that is performed internally. Try using DateTime.FromFileTimeUtc() instead, if at all possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消