Skip to content

Instantly share code, notes, and snippets.

Created January 2, 2013 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4432707 to your computer and use it in GitHub Desktop.
Save anonymous/4432707 to your computer and use it in GitHub Desktop.
Comparing return value with output parameter in C++
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> IntVec;
const int MAX = 10000;
IntVec Function1( const int size )
{
IntVec ivec;
for ( int i = 0; i < size; ++i )
ivec.push_back( i );
return ivec;
}
void Function2( const int size, IntVec& ivec )
{
for ( int i = 0; i < size; ++i )
ivec.push_back( i );
return;
}
int main()
{
// *** New Object
double time1 = 0.0;
double time2 = 0.0;
for ( int i = 0; i < MAX; ++i )
{
const int randVal = rand();
// *** Function1
clock_t begin1 = clock();
IntVec ivec1 = Function1( randVal );
clock_t end1 = clock();
double timeSec1 = (end1 - begin1) / static_cast<double>( CLOCKS_PER_SEC );
time1 += timeSec1;
// *** Function2
clock_t begin2 = clock();
IntVec ivec2;
Function2( randVal, ivec2 );
clock_t end2 = clock();
double timeSec2 = (end2 - begin2) / static_cast<double>( CLOCKS_PER_SEC );
time2 += timeSec2;
}
cout << "New object ..." << endl;
cout << "Function1: " << time1 << endl;
cout << "Function2: " << time2 << endl;
// *** Existing Object
time1 = 0.0;
time2 = 0.0;
IntVec ivec3;
for ( int i = 0; i < MAX; ++i )
{
const int randVal = rand();
// *** Function1
ivec3.clear();
clock_t begin1 = clock();
ivec3 = Function1( randVal );
clock_t end1 = clock();
double timeSec1 = (end1 - begin1) / static_cast<double>( CLOCKS_PER_SEC );
time1 += timeSec1;
// *** Function2
ivec3.clear();
clock_t begin2 = clock();
Function2( randVal, ivec3 );
clock_t end2 = clock();
double timeSec2 = (end2 - begin2) / static_cast<double>( CLOCKS_PER_SEC );
time2 += timeSec2;
}
cout << "Existing object ..." << endl;
cout << "Function1: " << time1 << endl;
cout << "Function2: " << time2 << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment