Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <assert.h>
- #include <iostream>
- #include <time.h>
- #include <string>
- #include <string.h>
- using namespace std;
- namespace g {
- bool wasCalled = false;
- }
- extern void doNothing( char const* ) { g::wasCalled = true; }
- class StopWatch
- {
- private:
- clock_t start_;
- clock_t end_;
- bool isRunning_;
- public:
- void start()
- {
- assert( !isRunning_ );
- start_ = clock();
- end_ = 0;
- isRunning_ = true;
- }
- void stop()
- {
- if( isRunning_ )
- {
- end_ = clock();
- isRunning_ = false;
- }
- }
- double seconds() const
- {
- return double( end_ - start_ )/CLOCKS_PER_SEC;
- }
- StopWatch(): start_(), end_(), isRunning_() {}
- };
- inline void testCStr( int const argc, char const* const argv0 )
- {
- // C-style character string implementation
- //const char *pc = "a very long literal string";
- const char *pc = (argc == 10000? argv0 : "a very long literal string");
- //const size_t len = strlen(pc +1); // space to allocate
- const size_t len = strlen(pc)+1; // space to allocate
- // performance test on string allocation and copy
- for (size_t ix = 0; ix != 1000000; ++ix) {
- char *pc2 = new char[len + 1]; // allocate the space
- strcpy(pc2, pc); // do the copy
- if (strcmp(pc2, pc) == 0) // use the new string
- //; // do nothing
- doNothing( pc2 );
- delete [] pc2; // free the memory
- }
- }
- inline void testCppStr( int const argc, char const* const argv0 )
- {
- // string implementation
- //string str("a very long literal string");
- string str( argc == 10000? argv0 : "a very long literal string" );
- // performance test on string allocation and copy
- for(int ix = 0; ix != 1000000; ++ix) {
- string str2 = str; // do the copy, automatically allocated
- if (str == str2) // use the new string
- //; // do nothing
- doNothing( &str2[0] );
- } // str2 is automatically freed
- }
- int main( int argc, char* argv[] )
- {
- StopWatch timer;
- timer.start(); testCStr( argc, argv[0] ); timer.stop();
- cout << "C strings: " << timer.seconds() << " seconds." << endl;
- timer.start(); testCppStr( argc, argv[0] ); timer.stop();
- cout << "C++ strings: " << timer.seconds() << " seconds." << endl;
- cout << boolalpha;
- cout << "doNothing was called = " << g::wasCalled << "." << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement