Re: Generally, are the programs written by C++ slower than written by
C 10% ?
On Sep 6, 3:40 pm, Asger-P <j...@asger-p.dk> wrote:
Hi Paavo Helde
On the: 06. of september-2011 At: 22:10 Paavo Helde wrote:
std::string test(cStr, L-1);
And yes, passing L here makes the tests more fair, as malloc/new got th=
e
size L, but std::string did not in the original version.
That is right, but then the std::string knows the length all
the way arround, so I think it would e fair to give the same
advantage to char array, like this.
int main(int argc, char* argv[])
{
clock_t tbeg;
char *cStr =
"123456789012345678901234567890123456789012345678901234567890";
const int L = strlen( cStr );
tbeg = clock();
for (int i = 0; i < 10000000; i++)
{
//std::string test(cStr, L);
//std::string test2 = test;
//test2 += test;
std::string test = cStr;
std::string test2;
test2.reserve(L*2);
test2.append(test).append(test);
if( test2[5] == '0' )
std::cout << "error" << std::endl;
}
std::cout << "test 1 use " << clock() - tbeg << std::endl;
tbeg = clock();
for (int i = 0; i < 10000000; i++)
{
char* str = new char[L+1];
strncpy(str, cStr, L);
char* str2 = new char[L*2 + 2];
strncpy(str2, str, L);
strncpy(&str2[L], str, L);
if( str2[5] == '0' )
std::cout << "error" << std::endl;
delete [] str;
delete [] str2;
}
std::cout << "test 2 use " << clock() - tbeg << std::endl;
tbeg = clock();
for (int i = 0; i < 10000000; i++)
{
char* str = (char*)malloc(L+1);
strncpy(str, cStr, L);
char* str2 = (char*)malloc(L*2 + 2);
strncpy(str2, str, L);
strncpy(&str2[L], str, L);
if( str2[5] == '0' )
std::cout << "error" << std::endl;
free(str);
free(str2);
}
std::cout << "test 3 use " << clock() - tbeg << std::endl;
getch();
return 0;
}
and then the numbers are really in favor of char array,
not the amount of coding though.
test 1 use 3744
Fixed it for you.
test 2 use 2090
test 3 use 1623