Consider the following code, which measures the time to perform 10
million string swapping.
#include <ctime>
#include <iostream>
#include <sys/time.h>
#define N 1000*1000*10
using std::string;
using std::cout;
using std::endl;
uint64_t GetTimeStamp() {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;
}
void swap(string& s1, string& s2)
{
string temp;
temp = s1;
s1 = s2;
s2 = temp;
}
int main()
{
string s1("Desk");
string s2("Table");
time_t start, end;
uint64_t t0, t1;
time(&start);
t0 = GetTimeStamp();
for (int i=0; i<N; ++i)
{
swap(s1, s2);
}
t1 = GetTimeStamp();
time(&end);
cout << "Elapsed time: " << (end-start) << " seconds." << endl;
cout << "Elapsed time: " << (t1 - t0)/1000000.0 << " seconds." << endl;
return 0;
}