AgentWeirdo AgentWeirdo - 1 month ago 8
C++ Question

Increase efficiency - parse integers from string C++

I have a string:


12:56:72


I need to get the 3 numbers (12, 56, and 72) individually.

I am doing:

int i=0,j=0,k=0,n, p[3]; // p[i] stores each ith value
char x[], b[];
x="12:34:56";
n=strlen(x);
while(i<strlen){
b[k]=x[i];
++i;
++k;
if(x[i==]':'){
p[j]=int(b);
++j;
++i;
k=0;
char temp[] = b;
b=new char[];
delete temp;
}
}


Can this be done more efficiently?

Answer

To be "more efficient", you will have to profile.

Here is another solution:

const std::string test_data("01:23:45");
unsigned int hours;
unsigned int minutes;
unsigned int seconds;
char separator;
std::istringstream input(test_data);
// Here's the parsing part
input >> hours >> separator >> minutes >> separator >> seconds;

Whether this is "more efficient" or not, must be measured.
It looks simpler and safer.

Edit 1: Method 2
Processors don't like loops or branches, so we can try to minimize. This optimization assumes perfect input as a string.

static const char test_data[] = "01:23:45";
unsigned int hours;
unsigned int minutes;
unsigned int seconds;
char c;
unsigned int index = 0;
hours = test_data[index++] - '0';
if (test_data[index] != ':')
{
  hours = hours * 10 + test_data[index++] - '0';
}
++index; // Skip ':'
minutes = test_data[index++] - '0';
if (test_data[index] != ':')
{
  minutes = minutes * 10 + test_data[index++] - '0';
}
++index; // Skip ':'
seconds = test_data[index++] - '0';
if (test_data[index] != ':')
{
  seconds = seconds * 10 + test_data[index++] - '0';
}

For highest optimizations, you have to make some assumptions. Another assumption is that the character encoding is UTF8 or ASCII, e.g. '1' - '0' == 1.

Comments