Faster alternative to DateTime.ParseExact

I parse a string in DateTime millions of times:

public static CultureInfo ci = CultureInfo.InvariantCulture;
while (!reader.EndOfStream)
{      
      line = reader.ReadLine();
      string[] fields = line.Split(' ');
      DateTime newDT = DateTime.ParseExact(fields[0], "yyyyMMddTHHmmssfff", ci);
}

My profiler allocates ParseExact as a huge part of the time. Is there another method / approach that could parse a string in a DateTime that would be faster?

FOLLOW UP1:

1) I tried this, but the speed was the same

bool OK = DateTime.TryParseExact(fields[0], "yyyyMMddTHHmmssfff", null, System.Globalization.DateTimeStyles.None,out DT);

2)

I tried to encode my own parser, but it was just as slow too:

public static DateTime fastParse(ref string s)
{
           return new DateTime(int.Parse(s.Substring(0,4)), int.Parse(s.Substring(4,2)),int.Parse(s.Substring(6,2)), int.Parse(s.Substring(9,2)),int.Parse(s.Substring(11,2)),int.Parse(s.Substring(13,2)),int.Parse(s.Substring(15, 3)));
}

FOLLOW UP2

I tried Master117 to suggest storing values ​​- AGAIN NO FASTER - perhaps a design problem?

     public class fastParseData
        {
            int year;
            int mon;
            int day;
            int hour;
            int min; 
            string previousSlice = "";

            public DateTime fastParse(ref string s)
            {
                if (previousSlice != s.Substring(0, 12))
                {
                     year=int.Parse(s.Substring(0,4));
                     mon=int.Parse(s.Substring(4,2));
                     day=int.Parse(s.Substring(6,2));
                     hour= int.Parse(s.Substring(9,2));
                     min = int.Parse(s.Substring(11,2));
                     previousSlice = s.Substring(0, 12);
                }

                return new DateTime(year, mon, day, hour,min, int.Parse(s.Substring(13, 2)), int.Parse(s.Substring(15, 3)));
            }

        }

FOLOW UP3

                public class fastParseData
                {
                    int year;
                    int mon;
                    int day;
                    int hour;
                    int min; 
                    string previousSlice = "";
                    DateTime previousDT;

                    public DateTime fastParse(ref string s)
                    {
                        if (previousSlice != s.Substring(0, 12))
                        {
                             year=int.Parse(s.Substring(0,4));
                             mon=int.Parse(s.Substring(4,2));
                             day=int.Parse(s.Substring(6,2));
                             hour= int.Parse(s.Substring(9,2));
                             min = int.Parse(s.Substring(11,2));
                             previousSlice = s.Substring(0, 12);
                            previousDT = new DateTime(year, mon, day, hour,min,0,0);
                        }
                        return previousDT.AddMilliseconds((int.Parse(s.Substring(13, 2))*1000)+int.Parse(s.Substring(15, 3)));
                    }

                }

FOLLOW UP4

From my profiler it seems like a problem

int.Parse(s.Substring(13, 2))

If the Parse bit is more expensive than the substring.

I tried

int.TryParse(s.Substring(13, 2),NumberStyles.None,ci, out secs)
Convert.ToInt32(s.Substring(13, 2));

but again - no difference in speed.

Is there a faster way to parse int?

+5
source share
5

, . , , . yyyyMMddTHHmmssfff : T

public class DateParser1
{
    private static System.String DateFormat="yyMMddTHHmmssfff";

    public static System.DateTime GetDate(System.String SourceString, int Offset=0) // Offset eliminates need for substring
    {
        int Year=0;
        int Month=0;
        int Day=0;
        int Hour=0;
        int Minute=0;
        int Second=0;
        int HourOffset=0;
        int MS=0;
        if(SourceString.Length+Offset<DateFormat.Length) throw new System.Exception(System.String.Format("Date Too Short {0} For {0}",SourceString.Substring(Offset),DateFormat));
        for(int i=0;i<DateFormat.Length;i++)
        {
            System.Char c=SourceString[Offset+i];
            switch(DateFormat[i])
            {
                  case 'y':
                      Year=Year*10+(c-'0');
                      break;
                  case 'M':
                      Month=Month*10+(c-'0');
                      break;
                  case 'd':
                      Day=Day*10+(c-'0');
                      break;
                  case 'T':
                      if(c=='p'||c=='P')
                           HourOffset=12;
                      break;
                  case 'h':
                      Hour=Hour*10+(c-'0');
                      if(Hour==12) Hour=0;
                      break;
                  case 'H':

                      Hour=Hour*10+(c-'0');
                      HourOffset=0;
                      break;
                  case 'm':
                      Minute=Minute*10+(c-'0');
                      break;
                  case 's':
                      Second=Second*10+(c-'0');
                      break;
                  case 'f':
                      MS=MS*10+(c-'0');
                      break;
            }

        }
        if(Year>30) //Change For Your Business Rules
        {
               Year+=1900;
        }
        else
        {
               Year+=2000;
        }
        try
        {
            return new System.DateTime(Year,Month,Day,Hour+HourOffset,Minute,Second,MS);
        }
        catch(System.Exception)
        {
            throw new System.Exception(System.String.Format("Error In Date: {0}/{0}/{0} {0}:{0}:{0}.{0} - {0} {0}",Year,Month,Day,Hour+HourOffset,Minute,Second,MS,DateFormat,SourceString.SubString(Offset,DateFormat.Length)));
        }
    }
}
+5

, //, Datetime Datetime,

DateTime newDT = DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32);

// , BUffer , , .

http://msdn.microsoft.com/de-de/library/vstudio/system.datetime.aspx

8 , string a = fields [0].slice(0,8) ( ), ints, , a = new a, ints , , , , a integers

, , , , ints /, , addSecond .., .

:

            public class fastParseData
            {
                int year;
                int mon;
                int day;
                int hour;
                int min; 
                string previousSlice = "";
                DateTime previousDT;

                public DateTime fastParse(ref string s)
                {
                    if (previousSlice != s.Substring(0, 12))
                    {
                         year=int.Parse(s.Substring(0,4));
                         mon=int.Parse(s.Substring(4,2));
                         day=int.Parse(s.Substring(6,2));
                         hour= int.Parse(s.Substring(9,2));
                         min = int.Parse(s.Substring(11,2));
                         previousSlice = s.Substring(0, 12);
                         previousDT = new DateTime(year, mon, day, hour,min,0,0);
                    }
                    return previousDT.ParseExact(year, mon, day, hour,min, int.Parse(s.Substring(13, 2)), int.Parse(s.Substring(15, 3));
                }

            }

, DT,

+2

, ( ). Release,.Net 4.5.2, 32- .

static void Main(string[] args)
{
    const string date = "2015-04-11T12:45:59";
    const string format = "yyyy-MM-ddTHH:mm:ss";

    var reference = FrameworkParse(date, format);
    var method1 = JamesBarrettParse(date, format);

    if (reference != method1)
    {
        throw new Exception(string.Format("reference date {0} does not match SO date {1}",reference.ToString("s"),method1.ToString("s")));
    }

    const int iterations = 1000000;
    var sw = new Stopwatch();

    //FRAMEWORK PARSE
    Console.Write("Starting framework parse for {0} iterations...", iterations);
    sw.Start();
    DateTime dt;
    for (var i = 0; i < iterations; i++)
    {
        dt = FrameworkParse(date, format);
        if (dt.Minute != 45)
        {
            Console.WriteLine("duh");
        }
    }
    sw.Stop();
    Console.WriteLine("DONE in {0} millis",sw.ElapsedMilliseconds.ToString("F2",CultureInfo.InvariantCulture));

    //James Barrett parse
    Console.Write("Starting JB parse for {0} iterations...", iterations);
    sw.Restart();
    for (var i = 0; i < iterations; i++)
    {
        dt = JamesBarrettParse(date, format);
        if (dt.Minute != 45)
        {
            Console.WriteLine("duh");
        }
    }
    sw.Stop();
    Console.WriteLine("DONE in {0} millis",sw.ElapsedMilliseconds.ToString("F2",CultureInfo.InvariantCulture));

    Console.Write("press any key to exit");
    Console.ReadKey();
}

private static DateTime FrameworkParse(string s, string format, CultureInfo info = null)
{
    var time = DateTime.ParseExact(s, format,
        info ?? CultureInfo.InvariantCulture,
        DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
    return time;
}

1000000 ... 2058.00
JB- 1000000 ... 324.00 . ,

+1

. Parallel.ForEach ,

private static IEnumerable<string> GetLines(TextReader reader)
{
    while (!reader.EndOfStream)
    {
         yield return reader.ReadLine();
    }
}

private static CultureInfo ci = CultureInfo.InvariantCulture;

public static ConcurrentBag ProcessData(TextReader reader)
{
    ConcurrentBag <DateTime> results = new ConcurrentBag <DateTime>();
    char[] seperators = {' '};

    Parallel.ForEach(GetLines(reader), line =>
    {
        //We only need the first field so limit the split to 2
        string[] fields = line.Split(seperators, 2);
        results.Enqueue(DateTime.ParseExact(fields[0], "yyyyMMddTHHmmssfff", ci));
    });

    return results
}

, , Parallel.ForEach, IEnumerable. (, ConcurrentDictionary<long,DateTime> Tuple<long,DateTime> ), .

0

Not sure if this will be faster, but you can convert the date string to a long one and then break it up arithmetically as follows:

string dateStr = "20131108134701234"; //yyyyMMddHHmmssfff
long dateLong = long.Parse(dateStr);

int f = (int) (dateLong % 1000);
int s = (int) ((dateLong % 100000 - f) / 1000);
int mi = (int) ((dateLong % 10000000 - s - f) / 100000);
int h = (int) ((dateLong % 1000000000 - mi - s - f) / 10000000);
int d = (int) ((dateLong % 100000000000 - h - mi - s - f) / 1000000000);
int mo = (int) ((dateLong % 10000000000000 - d - h - mi - s - f) / 100000000000);
int y = (int) ((dateLong % 100000000000000000 - mo - d - h - mi - s - f) / 10000000000000);

DateTime dateDT = new DateTime(y, mo, d, h, mi, s, f);

(naive, non-optimized implementation)

0
source

All Articles