Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate program execution time

Tags:

c

windows

I have a program in C which has to execute a series of another programs. I need to get the execution time of each of these programs, in order to create a log of these times.

I though of using system() to run each program, but I don't know how to get the execution time. Is there any way to do this?

The programs are "quick", so I need more precision than seconds.

like image 421
Jorgel Avatar asked Apr 16 '26 18:04

Jorgel


1 Answers

You have at least 4 ways to do it.

(1)

A start point:

 #include <stdio.h>
 #include <stdlib.h>
 #include <time.h>

 int main ( void )
 {
    clock_t start = clock();

    system("Test.exe");

    printf ("%f\n seconds", ((double)clock() - start) / CLOCKS_PER_SEC);
    return 0;
 }

(2)

If you are in Windows and you have access to Window APIs you can use GetTickCount() too:

 #include <stdio.h>
 #include <stdlib.h>
 #include <windows.h>


 int main ( void )
 {
    DWORD t1 = GetTickCount();

    system("Test.exe");

    DWORD t2 = GetTickCount();

    printf ("%i\n milisecs", t2-t1);
    return 0;
 }

(3)

And the best is

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main(void)
{
    LARGE_INTEGER frequency;
    LARGE_INTEGER start;
    LARGE_INTEGER end;
    double interval;

    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&start);

    system("calc.exe");

    QueryPerformanceCounter(&end);
    interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart;

    printf("%f\n", interval);

    return 0;
}

(4)

Question is tagged as C but for sake of completeness, I want add C++11 feature:

int main()
{
  auto t1 = std::chrono::high_resolution_clock::now();

  system("calc.exe");

  auto t2 = std::chrono::high_resolution_clock::now();
  auto x = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count();

  cout << x << endl;
}
like image 93
masoud Avatar answered Apr 19 '26 09:04

masoud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!