I need to convert fast the string in format “HHmmss” to DateTime or integers. I’ve tested such code:
Console.WriteLine("decoding " + text);
long microseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
Console.WriteLine("start time " + microseconds);
field = DateTime.ParseExact(text, "HHmmss", null);
microseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
Console.WriteLine("finish time " + microseconds);
and the output is
decoding 172400 start time 121 finish time 244 decoding 172400 start time 236 finish time 383 decoding 172400 start time 116 finish time 416 decoding 172400 start time 235 finish time 421 decoding 172359 start time 149 finish time 323
so in average about 150 microseconds. What’s a lot of time, i’m writing HFT software and the best HFT has in average 10 microseconds “tick-to-trade” time (this includes everything!). I understand that using c# this is imposible however i still think that 150 microseconds is too much even using c#.
Now I want to use another algorithm, however I don’t know how to “extract” integers from the text:
field = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, /*extract hour, min, sec from text*/)
What can you suggest and what would be the fastest way?
Please do not ask why I’m care about perfomance instead just suggest how to do that faster.
Results:
Using DateTime.ParseExact(text, "HHmmss", null) about 6-8 ticks
Using TimeSpan ts = TimeSpan.ParseExact(text, "hhmmss", null); about 3-4 ticks
Using int hour = 10 * text[0] + text[1] - 11 * '0';… about 0 ticks
Acutally much less than 0 ticks if using loop for measurements. Actually it was found that last version is 100 times faster than other.
Code:
long startMicroseconds = sw.ElapsedTicks /*/ (Stopwatch.Frequency / (1000L * 1000L))*/;
//TimeSpan ts = TimeSpan.ParseExact(text, "hhmmss", null);
//int hour = 10 * text[0] + text[1] - 11 * '0';
//int minute = 10 * text[2] + text[3] - 11 * '0';
//int second = 10 * text[4] + text[5] - 11 * '0';
field = DateTime.ParseExact(text, "HHmmss", null);
long finishMicroseconds = sw.ElapsedTicks /*/ (Stopwatch.Frequency / (1000L * 1000L))*/;
Console.WriteLine("elappsed " + (finishMicroseconds - startMicroseconds));
This approach doesn’t use any string substring or parsing methods. It uses only indexing and simple arithmetic:
This next version is probably even faster because the calculation has been partially evaulated to help the compiler. As a result it is slightly harder to read and understand:
For kicks you might also want to see if this is even faster, though I suspect that this code will be the same as the previous version: