m.Mig
m.Mig

Reputation: 21

how to execute the running time of a program written in c++?

I have code that generates random numbers from 1-100 and sorts them using the merge sort which I already have in a separate function. Everything works but when I implement clock(); to try and get the running time, I always get zero. I have even tried with larger numbers like 10000 but still, the time passed always gives me zero. here is my code

int main() {
clock_t startTime;
clock_t endTime;
clock_t timePassed;

int array[100];
srand(time(NULL));
int n = sizeof(array) / sizeof(array[0]);
startTime = clock();
    for (int j = 0; j < 100; j++)
    {
        array[j] = rand() % 100+1;
        std::cout << array[j] << " ";
    }
    std::cout << "\n";
    MergeSort(array, n);

    std::cout << "After Merge Sort :" << std::endl;
    PrintArray(array, n);

    endTime = clock();
    timePassed = ((endTime - startTime) / CLOCKS_PER_SEC);
    std::cout << "\n" << timePassed;
}
return 0;
}

Upvotes: 0

Views: 122

Answers (2)

Swordfish
Swordfish

Reputation: 13144

use

double timePassed = (endTime - startTime) / static_cast<double>(CLOCKS_PER_SEC);

Plan B for higher accuracy:

#include <iostream>
#include <chrono>

// ...

auto start_time{ std::chrono::high_resolution_clock::now() };

// ... code you want to time

auto end_time{ std::chrono::high_resolution_clock::now() };

std::cout << std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time).count() << ":";
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count() << ":";

// ...

Upvotes: 1

GizMoCuz
GizMoCuz

Reputation: 13

If you are developing on a Unix system and want to measure the execution time from an application, you can also use the 'time' command like:

time myapplication

see time (Unix) - Wikipedia

Upvotes: 0

Related Questions