8
votes

I would like to know what lines of C code to add to a program so that it tells me the total time that the program takes to run. I guess there should be counter initialization near the beginning of main and one after the main function ends. Is the right header clock.h?

Thanks a lot...

Update I have a Win Xp machine. Is it just adding clock() at the beginning and another clock() at the end of the program? Then I can estimate the time difference. Yes, you're right it's time.h.

Here's my code:

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


void f(long double fb[], long double fA, long double fB);

int main() {

clock_t start, end;
start = clock();


const int ARRAY_SIZE = 11;

long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE);

int i;
long double A, B;

if (z == NULL) {
    printf("Out of memory\n");
    exit(-1);
}

A = 0.5;
B = 2;


for (i = 0; i < ARRAY_SIZE; i++) {
    z[i] = 0;
}

z[1] = 5;

f(z, A, B);

for (i = 0; i < ARRAY_SIZE; i++)
    printf("z is %.16Le\n", z[i]);



free(z);
z = NULL;

end = clock();
printf("Took %ld ticks\n", end-start);
printf("Took %f seconds\n", (double)(end-start)/CLOCKS_PER_SEC);



return 0;  
}  

void f(long double fb[], long double fA, long double fB) {
    fb[0] = fb[1]* fA;
    fb[1] = fb[1] - 1;
    return;
 }  

Some errors with MVS2008:

testim.c(16) : error C2143: syntax error : missing ';' before 'const'  
testim.c(18) :error C2143: syntax error : missing ';' before 'type'  
testim.c(20) :error C2143: syntax error : missing ';' before 'type'   
testim.c(21) :error C2143: syntax error : missing ';' before 'type'    
testim.c(23) :error C2065: 'z' : undeclared identifier   
testim.c(23) :warning C4047: '==' : 'int' differs in levels of indirection from 'void *'  
testim.c(28) : error C2065: 'A' : undeclared identifier
testim.c(28) : warning C4244: '=' : conversion from 'double' to 'int', possible loss of data   

and it goes to 28 errors. Note that I don't have any errors/warnings without your clock codes.

LATEST NEWS: I unfortunately didn't get a good reply here. But after a search on Google, the code is working. Here it is:

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


void f(long double fb[], long double fA);

int main() {

clock_t start = clock();


const int ARRAY_SIZE = 11;

long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE);

int i;
long double A;

if (z == NULL) {
printf("Out of memory\n");
exit(-1);
}

A = 0.5;


for (i = 0; i < ARRAY_SIZE; i++) {
z[i] = 0;
}

z[1] = 5;

f(z, A);

for (i = 0; i < ARRAY_SIZE; i++)
printf("z is %.16Le\n", z[i]);



free(z);
z = NULL;

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



return 0;
}

void f(long double fb[], long double fA) {
fb[0] = fb[1]* fA;
fb[1] = fb[1] - 1;
return;
}

Cheers

Update on April 10: Here's a better solution thanks to "JustJeff"

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

void f(long double fb[], long double fA);

const int ARRAY_SIZE = 11;

int main(void)
{

   long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE);
   int i;
   long double A;

   LARGE_INTEGER freq;
   LARGE_INTEGER t0, tF, tDiff;
   double elapsedTime;
   double resolution;

   if (z == NULL) {
   printf("Out of memory\n");
   exit(-1);
   }
   QueryPerformanceFrequency(&freq);
   QueryPerformanceCounter(&t0);
   // code to be timed goes HERE
   {
    A = 0.5;


    for (i = 0; i < ARRAY_SIZE; i++) {
    z[i] = 0;
    }

    z[1] = 5;
    f(z, A);


    for (i = 0; i < ARRAY_SIZE; i++)
    printf("z is %.16Le\n", z[i]);

    free(z);
    z = NULL;

   }
QueryPerformanceCounter(&tF);
tDiff.QuadPart = tF.QuadPart - t0.QuadPart;
elapsedTime = tDiff.QuadPart / (double) freq.QuadPart;
resolution = 1.0 / (double) freq.QuadPart;
printf("Your performance counter ticks %I64u times per second\n", freq.QuadPart);
printf("Resolution is %lf nanoseconds\n", resolution*1e9);
printf("Code under test took %lf sec\n", elapsedTime);
return 0;
}


void f(long double fb[], long double fA) {
fb[0] = fb[1]* fA;
fb[1] = fb[1] - 1;
return;
}

It works both with MVS2008 and with Borland C++ builderX from 2003.

6
You can post an answer and accept it if you feel you now have the best answer yourself. Doing so can be helpful to someone else searching for an answer to the question at hand (and I'm sure other people search for this all the time).Cam
I don't know if I have the right answer. But it's working. I always welcome constructive suggestions as I'm still learning. Can I accept (place a tick) my own answer?yCalleecharan
Yes, you can. And by the way, don't mean to be rude, but how didn't you get a good reply here? You got a couple of nice answers which should work. If you get errors, that's your own code, not what the answerers gave you. If you don't think the answers you got are good, please say how so we can improve them.Javier
I tested the suggestions here with MVS2008 and I've been getting errors as I mentioned in my post. I'm a novice in C programming. I can't say why the suggested codes here are not working. I got an answer from Google, tested it with my code and it seems to be working. As I improve my knowledge of C with time, I can come back someday and point out any mistakes if any in the suggested codes here. There might be something with my own code. I don't know this yet. I'm here to learn and share knowledge. With my limited knowledge in C, it's hard for me to be the information giver but this will change.yCalleecharan

6 Answers

1
votes

If you're on windows and you want to measure stuff down in the microseconds, investigate QueryPerformanceCounter() and QueryPerformanceFrequency(). On many systems these can resolve full processor clock periods, third of a nanosecond stuff, and I don't believe I've ever seen it any more coarse than 3.5795MHz, still well under a microsecond.

You call QueryPerformanceFrequency() to determine how many counts per second the counter counts. Then call QueryPerformanceCounter() before your code under test, and then again after. Delta the two readings of QPC and divide by the period from QPF and you get the elapsed time between the two QPC calls. Like so ...

LARGE_INTEGER freq;
LARGE_INTEGER t0, tF, tDiff;
double elapsedTime;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t0);
// code to be timed goes HERE
QueryPerformanceCounter(&tF);
tDiff.QuadPart = tF.QuadPart - t0.QuadPart;
elapsedTime = tDiff.QuadPart / (double) freq.QuadPart;
// elapsedTime now has your measurement, w/resolution given by freq

Evidently these access a hardware counting device that is tied to some system oscillator on the main board, in which case they shouldn't suffer jitter from software load. The resolution you get depends on your system.

FOLLOW UP

Here's a very simple complete program that demonstrates the interface:

#include <windows.h>
int main(void)
{
    LARGE_INTEGER freq;
    LARGE_INTEGER t0, tF, tDiff;
    double elapsedTime;
    double resolution;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&t0);
    // code to be timed goes HERE
    {
        Sleep(10);
    }
    QueryPerformanceCounter(&tF);
    tDiff.QuadPart = tF.QuadPart - t0.QuadPart;
    elapsedTime = tDiff.QuadPart / (double) freq.QuadPart;
    resolution = 1.0 / (double) freq.QuadPart;
    printf("Your performance counter ticks %I64u times per second\n", freq.QuadPart);
    printf("Resolution is %lf nanoseconds\n", resolution*1e9);
    printf("Code under test took %lf sec\n", elapsedTime);
    return 0;
}

For something as simple as this, it's quicker to skip the IDE, just save it in a foo.c file and (assuming MS VS 2008) use the command line

cl foo.c

to build it. Here's the output on my system:

Your performance counter ticks 3579545 times per second
Resolution is 279.365115 nanoseconds
Code under test took 0.012519 sec
6
votes

On Unix (I think) systems, the time command with the name of your program as a command-line argument will tell you the time the program takes to run. Note that this measures the execution time of the whole program. If you need to test just one part, include time.h and use the clock function, more or less like this:

#include <time.h>

int main() {
    clock_t start;
    clock_t end;
    int function_time;
    start = clock();
    function_you_want_to_time();
    end = clock();
    /* Get time in milliseconds */
    function_time = (double)(end - start) / (CLOCKS_PER_SEC / 1000.0);
    return 0;
}

That will give you the time in milliseconds (notice the / 1000.0 part). If you want seconds, remove / 1000.0. If you want plain clock ticks, which will be more accurate, make function_time a clock_t and replace the function_time = ... line with:

function_time = end - start;

To time the whole program, I suggest to make a function called _main() or something, move all your program related code from main() (not the timing code!) to that function, and calling it from main(). That way, it's more clear what's the timing code and what's the rest of the program.

3
votes

If you need a total for your program then in Linux console:

$ time myProgram

You can also use time.h in your code.

#include <time.h>

int main(){
  time_t start, end;
  start = time(0);

  /* some working code */

  end = time(0);
  printf("%i seconds", end - start );
}
3
votes

You could use the clock() function (in <time.h>) if you want to test a block of code, or the time program on *nix, as another answerer suggested. E.g.

> time ./foo my args

For clock, you need to subtract the difference between two checkpoints. E.g.

#include <time.h>

void f() {
  clock_t start, end;

  start = clock();

  // some long code.

  end = clock();
  printf("Took %ld ticks\n", end-start);
  // or in (fractional) seconds.
  printf("Took %f seconds\n", (double)(end-start)/CLOCKS_PER_SEC);
}

Update

Regarding your new errors, you can't mix code and declarations in VC. You mustn't call any functions then continue to declare variables. Declare all your vars at the top, or compile with C++ mode.

1
votes

You probably want time.h, and the clock() function.

0
votes

You can try GetTickCount also. Clock will also work fine. But, I guess clock values will change if some other process or some one manually changes the system time, wheareas GetTickCount values are not affected by that.