How to use <chrono> in order to see how much time a function took to execute

I have to compare the time differentiation between bubble sort, selection sort, linear search, and binary search functions. I have already completed all of my functions, but every time I display execution time, it displays a 0. Anyway around this, or do I have to change something about my formatting... My time display starts at the end of case 1. I did not include my other functions into this example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
 using namespace std;
using std::time;
using namespace std::chrono;

int Menu(); // Menu for sorting and search options.
void bubbleSort(int [], int); // Applies bubble sort algorithm to sort the elements of an unsorted array
void selectionSort(int [], int); // Applies selection sort algorithm to sort the elements of an unsorted array
int linearSearch(int [], double[], int, int ); // Applies the linear search algorithm to search for book ID
int binarySearch(int [], double [], int, int); // Applies the binary search algorithm to search for book ID
void display(string [], int [], double [], int); // To display the contents of parallel array in a tabular format



int main()
{

    int size = 10, choice, searchKey, searchKey2, result, result2, quantity=0, quantity2=0;
    const int SIZE = 1000; // Constant max for number of numbers random number generator will output
    const int MAXRANGE = 500; // Constant range for the range of numbers random number generator will sort through
    int selectionsort[ SIZE ] = {0};
    int bubblesort[ SIZE ] = {0};
    time_t t;
    srand((unsigned) time(&t));


    string bookTitle[] = {"Starting out with C++", "Java Programming", "Software Structures",
    "Design and Analysis of Algorithms", "Computer Graphics", "Artificial Intelligence: A Modern Approach",
    "Probability and Statistics", "Cognitive Science", "Modern Information Retrieval", "Speech and Language Processing"};   // Parallel Arrays

    int bookID[] = {1101, 1211, 1333, 1456, 1567, 1642, 1699, 1755, 1800, 1999};

    double bookPrice[] = {112.32, 73.25, 54.00, 67.32, 135.00, 173.22, // Use of parallel arrays to match data with book ID and price
    120.00, 42.25, 32.11, 123.75};



    while (choice != 5) // Loops as long as user does not enter 5
    {
        choice = Menu();
        if (choice == 5){
         cout << "Thanks for stopping by! Please, do come again soon :)";   break;} // Program terminates if user enters 5
        switch (choice)
        {
        case 1:
            display(bookTitle, bookID, bookPrice, size); // Displays book title, ID, and price using arrays
            cout << "***LINEAR SEARCH***" << endl;
            cout << "Please enter a book ID to purchase: ";
            cin >> searchKey;
            result = linearSearch(bookID, bookPrice, size, searchKey);
            if (result >=0){ // Searches in the array for value user enters, this way it will find the price of each book.

                cout << "The book " << bookTitle[result] << " was chosen." << endl;
                cout << "Please enter how many you would like to purchase: ";
            result = linearSearch(bookID, bookPrice, size, searchKey);
                cin >> quantity; // Quantity used in order to count number of books using the array the user wishes to purchase.
                cout << "You have purchased " << quantity << " " << bookTitle[result] << endl << "For the total price of $" << bookPrice[result] * quantity << endl;
                cout << "Thank you for your business!" << endl << endl;
                high_resolution_clock::time_point t1 = high_resolution_clock::now();
                linearSearch(bookID, bookPrice, size, searchKey);
                high_resolution_clock::time_point t2 = high_resolution_clock::now();

                auto duration = duration_cast<microseconds>( t2 - t1 ).count();

                cout << "The time the process took is " << duration << " milliseconds" << endl << endl;
            } 
> every time I display execution time, it displays a 0.

The sequences are too small; the time taken is under a single clock tick.
Use larger sequences, say a million elements each.

Use std::chrono::steady_clock to measure elapsed time.
Use std::clock to measure processor time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <chrono>
#include <ctime>
#include <string>
#include <vector>
#include <random>
#include <algorithm>
#include <cstdlib>

struct timer
{
    std::string label ;
    std::chrono::steady_clock::time_point start_c = std::chrono::steady_clock::now() ;
    std::clock_t start_p = std::clock() ;

    explicit timer( const std::string& label ) : label(label) {}

    ~timer()
    {
        const auto end_p = std::clock() ;
        const auto end_c = std::chrono::steady_clock::now() ;
        using namespace std::chrono ;
        std::cout << label << "\n--------------------\n"
                  << duration_cast<milliseconds>( end_c - start_c ).count() << " milliseconds elapsed\n"
                  << ( end_p - start_p ) * 1000.0 / CLOCKS_PER_SEC << " milliseconds processor\n" ;
    }
};

int compare( const void* pa, const void* pb )
{
    const auto a = *static_cast< const std::size_t* >(pa) % 10 ;
    const auto b = *static_cast< const std::size_t* >(pb) % 10 ;
    return (a>b) - (b>a) ;
}


int main()
{
    const std::size_t N = 1'000'000 ;
    std::vector< std::size_t > numbers(N) ;
    std::generate_n( numbers.begin(), N, std::mt19937( std::time(nullptr) ) ) ;
    
    // time sort scending on last digit 
    
    {
        auto cpy = numbers ;
        timer time_std_sort( "C++ std::sort" ) ;
        std::sort( cpy.begin(), cpy.end(), [] ( auto a, auto b ) { return a%10 < b%10 ; } ) ;
    }

    {
        auto cpy = numbers ;
        timer time_qsort( "\nC std::qsort" ) ;
        std::qsort( &cpy.front(), cpy.size(), sizeof( cpy.front() ), compare ) ;
    }

    {
        auto cpy = numbers ;
        timer time_qsort( "\nC++ std::stable_sort" ) ;
        std::stable_sort( cpy.begin(), cpy.end(), [] ( auto a, auto b ) { return a%10 < b%10 ; } ) ;
    }
}

C++ std::sort
--------------------
31 milliseconds elapsed
30 milliseconds processor

C std::qsort
--------------------
286 milliseconds elapsed
290 milliseconds processor

C++ std::stable_sort
--------------------
97 milliseconds elapsed
90 milliseconds processor

--------- g++/libstdc++ ------------

C++ std::sort
--------------------
65 milliseconds elapsed
60 milliseconds processor

C std::qsort
--------------------
221 milliseconds elapsed
220 milliseconds processor

C++ std::stable_sort
--------------------
137 milliseconds elapsed
140 milliseconds processor

http://coliru.stacked-crooked.com/a/11324ccc80978ca8
How would I implement this in a case by case scenario, my program has 4 cases.
Make these arrays much larger, with several thousand elements. (Generate the id and price randomly.)
:
1
2
3
4
int bookID[] = {1101, 1211, 1333, 1456, 1567, 1642, 1699, 1755, 1800, 1999};

double bookPrice[] = {112.32, 73.25, 54.00, 67.32, 135.00, 173.22, // Use of parallel arrays to match data with book ID and price
    120.00, 42.25, 32.11, 123.75};


I don't think I can do that, with the user having to search for an ID, the book shows up, and the price for said book. If I generate them randomly, it would output garbage if the user typed in a ID that didn't have a book to go with it.
Ignore valid (or any) output while making performance measurements.

For instance, 500 linear searches in a sequence of one million elements takes less than a second.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <chrono>
#include <ctime>
#include <string>
#include <random>
#include <algorithm>
#include <iomanip>

struct timer
{
    std::string label ;
    std::chrono::steady_clock::time_point start_c = std::chrono::steady_clock::now() ;
    std::clock_t start_p = std::clock() ;

    explicit timer( const std::string& label ) : label(label) {}

    ~timer()
    {
        const auto end_p = std::clock() ;
        const auto end_c = std::chrono::steady_clock::now() ;
        using namespace std::chrono ;
        std::cout << label << "\n--------------------\n"
                  << duration_cast<milliseconds>( end_c - start_c ).count() << " milliseconds elapsed\n"
                  << ( end_p - start_p ) * 1000.0 / CLOCKS_PER_SEC << " milliseconds processor\n" ;
    }
};

long long random_id(  std::mt19937& rng, int min_v = 1000000,  int max_v = 9999999 )
{ return std::uniform_int_distribution<long long>{ min_v, max_v }(rng) ; }

double random_price(  std::mt19937& rng, double min_v = 10.00,  double max_v = 99.99 )
{ return std::uniform_real_distribution<double>{ min_v, max_v }(rng) ; }

int main()
{
    std::mt19937 rng( std::time(nullptr) ) ;

    constexpr std::size_t N = 1'000'000 ;

    static long long id[N] ;
    std::generate_n( id, N, [&rng] { return random_id(rng) ; } ) ;

    static double price[N] ;
    std::generate_n( price, N, [&rng] { return random_price(rng) ; } ) ;

    {
        const int N_SEARCH = 500 ;
        std::size_t pos[N_SEARCH] ;
        long long search_id[N_SEARCH] ;
        std::generate_n( search_id, N_SEARCH, [&rng] { return random_id(rng) ; } ) ;
        
        std::cout << N_SEARCH << " calls to std::find " << " in a sequence of " << N << " integers" ;
        {
            timer timer_find( "" ) ;
            for( std::size_t i = 0 ; i < N_SEARCH ; ++i ) pos[i] = std::find( id, id+N, search_id[i] ) - id ;
        }

        std::cout << '\n' << std::fixed << std::setprecision(2) ;
        for( std::size_t i = 0 ; i < N_SEARCH ; ++i )
        {
            if( pos[i] != N ) std::cout << std::setw(2) << i << ". " << "id: " << search_id[i] << " price: " << price[ pos[i] ] << '\n' ;
            // else std::cout << std::setw(2) << i << ". " << "id: " << search_id[i] << " not found\n" ;
        }
    }
}

500 calls to std::find  in a sequence of 1000000 integers
--------------------
769 milliseconds elapsed
760 milliseconds processor

http://coliru.stacked-crooked.com/a/aca740ac30af213d
Topic archived. No new replies allowed.