String Swap Time

  1. 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;
    }
    
    
  2. Try to add another block of code to perform the same number of string swapping with the inline expansion optimization technique. By removing the overhead of function calling, you can observe significant performance improvement. (On my computer, it is approximately 30%.)
  3. Try to write another block of code which invokes the string member function swap() that we learned in Chapter 18. Observe the performance improvement. (On my computer, it is approximate 90%.)