Re: Generally, are the programs written by C++ slower than written by C 10% ?
KaiWen <wenkai1987@gmail.com> wrote in
news:c7c6ebac-3a50-443e-a864-55f25df6ed54@g32g2000pri.googlegroups.com:
#include <iostream>
#include <string>
#include <cstring>
#include <clock.h>
int main() {
clock_t tbeg;
{
tbeg = clock();
for (int i = 0; i < 10000000; i++)
std::string("hello, world!");
std::cout << "test 1 use " << clock() - tbeg <<
std::endl;
}
{
tbeg = clock();
for (int i = 0; i < 10000000; i++) {
char* str = new char[20];
strcpy(str, "hello, world!");
delete [] str;
}
std::cout << "test 2 use " << clock() - tbeg <<
std::endl;
}
{
tbeg = clock();
for (int i = 0; i < 10000000; i++) {
char* str = (char*)malloc(20);
strcpy(str, "hello, world!");
free(str);
}
std::cout << "test 3 use " << clock() - tbeg <<
std::endl;
}
{
tbeg = clock();
for (int i = 0; i < 10000000; i++) {
char str[20];
strcpy(str, "hello, world!");
}
std::cout << "test 4 use " << clock() - tbeg <<
std::endl;
}
return 0;
}
output:
----------------------------
test 1 use 1260000
test 2 use 850000
test 3 use 610000
test 4 use 20000
My results (MSVC2010, Release x64 build):
test 1 use 160
test 2 use 476
test 3 use 417
test 4 use 0
The absolute values are not interesting as the clock() tick length is
platform-specific. However, std::string is much faster here than
malloc/new. I guess the small string optimization kicked in so
std::string did not perform any dynamic memory allocation at all.
Test 4 probably got optimized away completely.
cheers
Paavo