// CSCI 2720 Data Structures Spring 2004 // timedemo.cc // demonstration of timing function #include using namespace std; int main( ) { int i, j, flag, count, MAX = 50000; clock_t clock1, clock2; // declare variables to store times, in clock ticks clock1 = clock( ); // call just before code segment to time count = 0; for (i = 2; i <= MAX; i++) { flag = 1; for (j = 2; j*j <= i; j++) { if (i % j == 0) { flag = 0; break; } } count += flag; }; //for loop over i clock2 = clock( ); // call just after code segment to time cout << "starting time: " << clock1 << " in ticks.\n"; cout << "finish time: " << clock2 << endl; cout << "net CPU Time = " << (clock2 - clock1)/(CLOCKS_PER_SEC/1.0e3); cout << " milliseconds.\n\n"; cout << "no. primes =< " << MAX << " is: " << count << '\n' << endl; cout << "The next run should be slower, but give the same result.\n" << endl; clock1 = clock( ); // record start time, as in 1st run count = 0; for (i = 2; i <= MAX; i++) { flag = 1; for (j = 2; j*j <= i; j++) { if (i % j == 0) flag = 0; } count += flag; }; //for loop over i clock2 = clock( ); // record finish time, as in 1st run cout << "second starting time: " << clock1 << " in ticks.\n"; cout << "second finish time: " << clock2 << endl; cout << "second net CPU Time = " << (clock2 - clock1)/(CLOCKS_PER_SEC/1.0e3); cout << " milliseconds.\n\n"; cout << "no. primes =< " << MAX << " is: " << count << '\n' << endl; return 0; }