3

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.

1
  • What is your operating system? Commented Mar 5, 2013 at 17:01

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

The clock() thing shouldn't work. clock() is supposed to return the best approximation to the CPU time used by the programme, it shouldn't count the time used by a system()-invoked programme (and it doesn't here, may be different on Windows).
0
    start = clock();  // get number of ticks before loop
     /*
      Your Program
    */

    stop  = clock();  // get number of ticks after loop
    duration = ( double ) (stop - start ) / CLOCKS_PER_SEC;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.