Advertisement
janac

Measure elapsed time

Dec 22nd, 2021
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <chrono> // steady_clock
  3. #include <cstdlib> // rand(), srand()
  4. #include <ctime> // time()
  5. using namespace std;
  6.  
  7. // Time how fast you can multiply two numbers.
  8. int main()
  9. {
  10.     srand(time(NULL)); // Prepare random number generator.
  11.     int first_random_number = 0; // first number to multiply.
  12.     int second_random_number = 0; // first number to multiply.
  13.  
  14.     // Explain the program.
  15.     cout << "You will be given two numbers to multiply together.\n"
  16.         "\nTime yourself to see how fast you can do it.\n";
  17.     cout << "\nPress enter to see the numbers.\n"
  18.         "Press enter again when you have the answer.\n"
  19.         "You will see the correct answer and your time.\n";
  20.     cout << "\nPress ENTER when ready.\n";
  21.     cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Wait till ready.
  22.        
  23.     first_random_number = (rand() % 89) + 11; // Generate first number to multiply.
  24.     second_random_number = (rand() % 9) + 1; // Generate second number to multiply.
  25.  
  26.     cout << first_random_number << " * " << second_random_number << '\n'; // Display the problem.
  27.     chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); // Start timing.
  28.  
  29.     cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Wait till user is done.
  30.     chrono::steady_clock::time_point stop = std::chrono::steady_clock::now(); // Stop timing.
  31.  
  32.     float elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count(); // Calculate elapsed time.
  33.     float elapsed_time_seconds_decimal = elapsed_time / 1000; // Convert milliseconds to seconds.
  34.  
  35.     cout << "The answer is " << first_random_number * second_random_number << '\n'; // Display the answer.
  36.     cout << "\nYour time: " <<  elapsed_time_seconds_decimal << " seconds\n"; // Display how long it took.
  37.  
  38.     return 0; // End the program.
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement