Question

Lab 10A Measure the program execution time One easy way to measure the program execution time is ...

Lab 10A Measure the program execution time

One easy way to measure the program execution time is encapsulate the useful timing functionality of C++ chrono library, This is illustrated inhttps://www.learncpp.com/cpp-tutorial/8-16-timing-your-code/

The example usingChronoTimer.cpp (Github/m10) is an example program using this chrono Timer class object to measure the Sorting on on an integer array of 10000 random integers based on the Bubble Sort vs. the C++ built-in Sort (an https://www.quora.com/Which-sorting-algorithm-does-STL-standard-template-library-use-in-c++. )

Please measure the performance of sorting the same array used in the usingChronoTimer.cpp example between the Insertion Sort vs. the Selection Sort.

Starter

usingChronoTimer.cpp (Github/m10):

#include <chrono> // chrono
#include <cstdlib> // srand, rand
#include <ctime> // time
#include <algorithm> // sort
#include <iostream>
class Timer {
// Type aliases to make accessing nested type easier
using clock_t = std::chrono::high_resolution_clock;
using second_t = std::chrono::duration<double, std::ratio<1> >;
std::chrono::time_point<clock_t> m_beg;
public:
Timer() : m_beg(clock_t::now()) {}
void reset() { m_beg = clock_t::now(); }
double elapsed() const {
return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
}
};
void bubbleSort(int* a, int size) {
for(int i=0; i<size; i++)
for(int j=0; j<size-1; j++) {
if(a[j] > a[j+1]) {
int t = a[j]; a[j] = a[j+1]; a[j+1] = t;
}
}
}
void show(int *a) {
for(int i=0; i<5; i++)
std::cout << a[i] << " ";
std::cout << std::endl;
}
int main() {
const int Size = 10000;
int array1[Size];
int array2[Size];
srand (time(NULL));
int fill;
for(int i=0; i<Size; i++) {
array1[i] =array2[i] = rand() % 100003; // next prime 10X
}
show(array1);
show(array2);
Timer t1;
bubbleSort(array1, Size);
double run1 = t1.elapsed();
show(array1);
Timer t2;
std::sort(array2, array2+Size);
double run2 = t2.elapsed();
show(array2);
std::cout << "Bubble Sort Time: " << run1 << " seconds\n"
<< "CPP Sort Time: " << run2 << " seconds\n"
<< "Efficientcy: " << int( run1/run2 );
return 0;
}

Submit

  • myInsertionVsSelectionSortTime.cpp
  • test run result
0 0
Add a comment Improve this question Transcribed image text
Answer #1

cpp code:

#include <iostream>
#include <chrono> // chrono
#include <cstdlib> // srand, rand
#include <ctime> // time
#include <algorithm> // sort

using namespace std;

class Timer {
// Type aliases to make accessing nested type easier
using clock_t = std::chrono::high_resolution_clock;
using second_t = std::chrono::duration<double, std::ratio<1> >;
std::chrono::time_point<clock_t> m_beg;
  
public:
Timer() : m_beg(clock_t::now()) {}

void reset() { m_beg = clock_t::now(); }

double elapsed() const {
return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
}
};

//insertion sort
void insertionSort(int* a, int size)
{
int key,i,j;
for (i = 1; i < size; i++)
{
key = a[i];
j = i-1;

while (j >= 0 && a[j] > key)
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = key;
}
}
//swap function
void swap(int *x, int *y)
{
int t = *x;
*x = *y;
*y = t;
}

//selection sort function
void selectionSort(int* a, int size)
{
int i, j, min_idx;

for (i = 0; i <size -1; i++)
{
min_idx = i;
for (j = i+1; j < size; j++)
if (a[j] < a[min_idx])
min_idx = j;

// Swap the found minimum element with the first element
swap(&a[min_idx], &a[i]);
}
}
void show(int *a) {
cout << endl;
for(int i=0; i<5; i++)
cout << a[i] << " ";
cout << endl;
}
int main()
{
const int Size = 10000;
int array1[Size];
int array2[Size];
srand (time(NULL));
int fill;

for(int i=0; i<Size; i++) {
array1[i] =array2[i] = rand() % 100003; // next prime 10X
}
//cout<<"size: "<<Size;
show(array1);
show(array2);

//insertion sort
Timer t1;

insertionSort(array1, Size);

double run1 = t1.elapsed();
show(array1);

Timer t2;
std::sort(array2, array2+Size);
double run2 = t2.elapsed();
show(array2);

std::cout << "\n\nInsertion Sort Time: " << run1 << " seconds\n"
<< "CPP Sort Time: " << run2 << " seconds\n"
<< "Efficientcy: " << int( run1/run2 )<<endl;


//selection sort
Timer tt1;

selectionSort(array1, Size);

run1 = tt1.elapsed();
show(array1);

Timer tt2;
std::sort(array2, array2+Size);
run2 = tt2.elapsed();
show(array2);

std::cout << "\n\nSelection Sort Time: " << run1 << " seconds\n"
<< "CPP Sort Time: " << run2 << " seconds\n"
<< "Efficientcy: " << int( run1/run2 )<<endl;

return 0;
}

output:

2 DAcppInsertionVsSelectionSortTime\bin\Debug InsertionVsSelectionSortTime.exe 8824 20143 30741 15986 32161 8824 20143 30741

//for any clarification, please do comments. if you found this solution useful, please do comments

Add a comment
Know the answer?
Add Answer to:
Lab 10A Measure the program execution time One easy way to measure the program execution time is ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In this lab we are going to complete a profile of two sorting algorithms by running...

    In this lab we are going to complete a profile of two sorting algorithms by running some tests to collect empirical data. 1. First we need to be able to generate some random integers. You can do this by including the following library : #include Now first run the following to generate a seed : srand (time(NULL)) You can then generate a random number using the function rand() 2. We will use two sort algorithms - Selection Sort and Bubble...

  • My following program has an array which holds 1000 random integers between 1-1000. Now I need...

    My following program has an array which holds 1000 random integers between 1-1000. Now I need help to create an array that holds 10,000 random integer between 1-1000 in my following program. The main goal of this program is time analysis by using bubble sort and binary search algorithms. Please do the following task; 1. Replace the 1000 random integers with 10,000 random integers After change please answer the following question 2. what will be happen, if an array holds...

  • Merge Sort: Time Complexity: O(n log(n)) #include "stdafx.h" #include <iostream> #include <time.h> #include <stdlib.h> using namespace...

    Merge Sort: Time Complexity: O(n log(n)) #include "stdafx.h" #include <iostream> #include <time.h> #include <stdlib.h> using namespace std; void combine(int *a, int low, int high, int mid) {        int i, j, k, c[100000];        i = low;        k = low;        j = mid + 1;        while (i <= mid && j <= high)        {               if (a[i] < a[j])               {                      c[k] = a[i];                      k++;                      i++;               }               else               {                     ...

  • In below C++ sort.cpp 1- Implement the insertion_sort function. 2- Implement the compareSensorPtr function and the...

    In below C++ sort.cpp 1- Implement the insertion_sort function. 2- Implement the compareSensorPtr function and the code in main to create and sort the array of pointers. The places to make modifications are indicated by TODO: comments. You should not have to make modifications anywhere else. 3- what's big O and runtime for 100000 items. #include <iostream> #include <algorithm> #include <numeric> #include <vector> #include <string> #include <cstdlib> #include <cassert> using namespace std; // Set this to false to skip the...

  • Template Deque Class (C++) In this assignment, we will use a given test menu for the template Deq...

    Template Deque Class (C++) In this assignment, we will use a given test menu for the template Deque Class (a Linked List based Double Ended Queue, Deque) that you have put together. Recommended Steps testDeque.cpp : // C++ implementation of doubly linked list Deque doubly linked list #include <bits/stdc++.h> using namespace std; class Timer { // To replace with the full timer class definition // inside this folder: LearnCpp9_18_timeSortArray.cpp }; // Node of a doubly linked list template<class T> class...

  • The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also...

    The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also please explain why the seg fault is happening. Thank you #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // @Name loadMusicFile // @Brief Load the music database // 'size' is the size of the database. char** loadMusicFile(const char* fileName, int size){ FILE *myFile = fopen(fileName,"r"); // Allocate memory for each character-string pointer char** database = malloc(sizeof(char*)*size); unsigned int song=0; for(song =0; song < size;...

  • Design a program that allows you to experiment with different sort algorithms in Java. This program should allow you to...

    Design a program that allows you to experiment with different sort algorithms in Java. This program should allow you to easily plug-in new sort algorithms and compare them. Assume that input data is generated randomly and stored in a text file (have no less than 2000 items to sort). Do not restrict your program to only one data type, or to one ordering relationship. The data type, ordering relationship, and the sorting method must be input parameters for your program....

  • Template Dequeue Class (C++ ) In this assignment, we will use a given test menu for the template ...

    Template Dequeue Class (C++ ) In this assignment, we will use a given test menu for the template Deque Class (a Linked List based Double Ended Queue, Deque) that you have put together. Starter testDeque.cpp which contains: Timer class holder (you need to go through the LearnCpp Ch15 and import it in) Node class Deque class specification (you need to fill out the definition) here is the testDeque.cpp code: // C++ implementation of doubly linked list Deque doubly linked list...

  • Hello, I want to check if my C++ code is correct and follows the requeriments described...

    Hello, I want to check if my C++ code is correct and follows the requeriments described thanks. Requeriments: Assignment Sorting Benchmark each of the sorting methods listed below. Insertion Sort Bubble Sort Selection Sort Heap Sort. Quick Sort. Merge Sort. Benchmark each of the above sorting methods for data sizes of 10000, 20000, 30000, 40000 and 50000. Display the results in a table as shown below. The table should have rows and columns. However, the rows and columns need not...

  • You are given a sample code that when edited/ improved/completed -will work as a producer consumer...

    You are given a sample code that when edited/ improved/completed -will work as a producer consumer synchronized solution. In addition to the counter, you will implement a circular linked list as a buffer of size 200 that stores data items 0 or 1. The producer and consumer take *random* turns to produce and consume- *random* numbers of elements ( turning 1 to a 0 and visa-versa-each time, as discussed in class). After each turn of the producer and/or consumer, your...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT