How to measure execution time of a code block in C++

1 Answer

0 votes
#include <iostream>
#include <chrono>

constexpr int LEN = 10000000;

void setNumbers(int arr[]) {
    std::srand(std::time(nullptr));
    
    for (size_t i = 0; i < LEN; i++) {
        arr[i] = std::rand();
    }
}

int main() {
    int *arr = new int[LEN];

    auto start = std::chrono::high_resolution_clock::now();
    
    setNumbers(arr);
    
    auto end = std::chrono::high_resolution_clock::now();

    std::chrono::duration<double, std::milli> duration_float = end - start;
    auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

    std::cout << duration_float.count() << " milliseconds";

    delete [] arr;
}
 
 
 
 
/*
run:
 
183.452 milliseconds
 
*/

 



answered May 16, 2021 by avibootz
edited May 16, 2023 by avibootz

Related questions

2 answers 291 views
1 answer 257 views
2 answers 268 views
1 answer 176 views
176 views asked Feb 21, 2022 by avibootz
4 answers 323 views
1 answer 105 views
...