Re: Generally, are the programs written by C++ slower than written
by C 10% ?
On 06/09/2011 20:04, Asger-P wrote:
Hi Paavo
Modified the test a little to make sure the std::string
actually was created, it makes quite a difference:
#include <iostream>
#include <string>
#include <cstring>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
int _tmain(int argc, char* argv[])
{
clock_t tbeg;
char *cStr = "123456789012345678901234567890";
const int L = strlen( cStr ) + 1;
tbeg = clock();
for (int i = 0; i < 10000000; i++)
{
std::string test(cStr);
if( test[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];
strcpy(str, cStr);
if( str[5] == '0' )
std::cout << "error" << std::endl;
delete [] str;
}
std::cout << "test 2 use " << clock() - tbeg << std::endl;
tbeg = clock();
for (int i = 0; i < 10000000; i++)
{
char* str = (char*)malloc(L);
strcpy(str, cStr);
if( str[5] == '0' )
std::cout << "error" << std::endl;
free(str);
}
std::cout << "test 3 use " << clock() - tbeg << std::endl;
getch();
return 0;
}
test 1 use 1451
test 2 use 998
test 3 use 749
why is malloc faster then new ??
Best regards
Asger-P
Lets change the conditions of the test slightly:
int main(int argc, char* argv[])
{
clock_t tbeg;
char *cStr =
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
const int L = strlen( cStr ) + 1;
tbeg = clock();
for (int i = 0; i < 10000000; i++)
{
std::string test(cStr, L);
std::string test2 = test;
test2 += 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];
strcpy(str, cStr);
char* str2 = new char[L*2];
strcpy(str2, str);
strcat(str2, str);
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);
strcpy(str, cStr);
char* str2 = (char*)malloc(L*2);
strcpy(str2, str);
strcat(str2, str);
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;
}
We get:
test 1 use 5460
test 2 use 7472
test 3 use 7410
Swings and roundabouts. Also if we use a very short string:
char *cStr = "12345";
We get:
test 1 use 1232
test 2 use 1654
test 3 use 1544
Again it is just swings and roundabouts. Even if on average std::string
performs slightly worse than C style strings the convenience that
std::string offers more than makes up for its performance shortcomings IMO.
/Leigh