2

there's a function that I want to test the time of: function()

I am not sure how to do this in C, here's the pseudocode of what I want to do:

int main()
{
int startTime = getTime();
function();
int endTime = getTime();
print endTime - startTime;
}

How is this done in C?

houbysoft
  • 32,532
  • 24
  • 103
  • 156
SuperString
  • 21,593
  • 37
  • 91
  • 122

6 Answers6

3

Unfortunately there is no way to do this using ANSI C. However, you can do it using gettimeofday, a POSIX function:

#include <sys/time.h>

struct timeval tv;
struct timeval start_tv;

gettimeofday(&start_tv, NULL);

// call your function here

double elapsed = 0.0;

gettimeofday(&tv, NULL);
elapsed = (tv.tv_sec - start_tv.tv_sec) +
  (tv.tv_usec - start_tv.tv_usec) / 1000000.0;

Alternatively, if you want the execution time of your entire program, you could also just run time ./your_program on the command line.

Finally, if you are on Windows, you can use the timeGetTime function.

houbysoft
  • 32,532
  • 24
  • 103
  • 156
  • do I need to import something? – SuperString Jul 05 '12 at 16:41
  • 1
    `gettimeofday(2)` isn't standard C, it's in POSIX. Also, `time` is called `timeit` on Windows and it's in the resource kit. – cha0site Jul 05 '12 at 16:42
  • @cha0site: I know, but there is no function in C that can do what he want (see http://stackoverflow.com/questions/361363/how-to-measure-time-in-milliseconds-using-ansi-c). – houbysoft Jul 05 '12 at 16:44
  • 2
    I think that the comment about it's being POSIX is sort of missing the point. In C, it is quite common to use `gettimeofday` and other non-standard timers, in practice. I don't think insisting that `time` is the only valid option is particularly helpful. – Patrick87 Jul 05 '12 at 16:45
  • @Patrick87: It is the only helpful option if he doesn't tell us what OS he uses... Windows simply doesn't have `gettimeofday(2)`. – cha0site Jul 05 '12 at 16:52
  • @cha0site: Fair enough, added a Windows alternative. – houbysoft Jul 05 '12 at 16:54
  • @cha0site Isn't it much more helpful to tell him that there are good options, depending on the system he intends to use? Another answer takes this into account by showing both `QueryPerformanceCounter` and `gettimeofday`. That might be the best answer here. – Patrick87 Jul 05 '12 at 16:54
  • @SuperString: tag your question then. – houbysoft Jul 05 '12 at 17:09
  • @Patrick87 You might be right, but that answer has the misfortune of being written in another language. Also, even though it covers both operating systems, country *and* western, I think it's important to be aware that standard C (Not just ANSI - C99 even!) doesn't really provide that much stuff. Only way to get time is `time`. Only way to sleep is busy wait. All I/O is with `FILE *` - and you can't multiplex it (no `select()`)... If someone asks you how to do those kinds of things in C, I think the only really valid responses are my answer or asking "What OS?" – cha0site Jul 05 '12 at 17:11
  • I am getting these errors when trying to get timeGetTime(): Error 1 error LNK2001: unresolved external symbol __imp__timeGetTime@0 Error 2 fatal error LNK1120: 1 unresolved externals – SuperString Jul 05 '12 at 17:15
1

This code runs function() 1 million times, then prints the average runtime of each function call.

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

int main(int argc, const char ** argv)
{
    time_t start, end;

    start = time(NULL);
    for (int i = 0; i < 1000000; ++i)
        function();
    end = time(NULL);

    printf("%f\n", (end - start) / 1000000.0);

    return 0;
}
cha0site
  • 10,517
  • 3
  • 33
  • 51
  • I'm not the downvoter, but `time` only has 1-second resolution, and thus is effectively useless for measuring performance. – houbysoft Jul 05 '12 at 16:38
  • @houbysoft: Sure, and yet it is the only way to measure time in C99. – cha0site Jul 05 '12 at 16:39
  • 1
    This answer could be worthwhile, for instance, if you mentioned how you might time many executions of `function()` in a tight loop. e.g., time 1,000,000 iterations, and divide by 1,000,000. – Patrick87 Jul 05 '12 at 16:41
  • I think this answer has some value, maybe if on an extremely limited system or wanting extremely portable code – Earlz Jul 05 '12 at 16:51
  • What about "7.27.2.1 The clock function"? (7.23 in C99) (regarding "the only way to measure time in C99") – Daniel Fischer Jul 05 '12 at 17:53
  • @Daniel: You're right, but note that that measures CPU time and not wall time. – cha0site Jul 05 '12 at 17:59
  • Yes. But I would think that for timing a function, CPU time is the better measure than wall-clock time. – Daniel Fischer Jul 05 '12 at 18:05
0

Look into the gettimeofday and/or clock functions. There may be more high-precision clocks/timers, but these should be sufficient for a good cross-section of code.

Patrick87
  • 27,682
  • 3
  • 38
  • 73
0

I always use this class (sorry, it is C++) I found somewhere ages ago. Sorry I don't know the author, but I guess it is OK to post it.

Usage:

Timer hello;
hello.start();
function();
hello.stop();
std::cout << "Total time in ms: " << hola.getElapsedTimeInMilliSec() << std::endl;

The class itself:

#include "timer.hh"
#include <stdlib.h>

///////////////////////////////////////////////////////////////////////////////
// constructor
///////////////////////////////////////////////////////////////////////////////
Timer::Timer()
{
#ifdef WIN32
    QueryPerformanceFrequency(&frequency);
    startCount.QuadPart = 0;
    endCount.QuadPart = 0;
#else
    startCount.tv_sec = startCount.tv_usec = 0;
    endCount.tv_sec = endCount.tv_usec = 0;
#endif

    stopped = 0;
    startTimeInMicroSec = 0;
    endTimeInMicroSec = 0;
}



///////////////////////////////////////////////////////////////////////////////
// distructor
///////////////////////////////////////////////////////////////////////////////
Timer::~Timer()
{
}



///////////////////////////////////////////////////////////////////////////////
// start timer.
// startCount will be set at this point.
///////////////////////////////////////////////////////////////////////////////
void Timer::start()
{
    stopped = 0; // reset stop flag
#ifdef WIN32
    QueryPerformanceCounter(&startCount);
#else
    gettimeofday(&startCount, NULL);
#endif
}



///////////////////////////////////////////////////////////////////////////////
// stop the timer.
// endCount will be set at this point.
///////////////////////////////////////////////////////////////////////////////
void Timer::stop()
{
    stopped = 1; // set timer stopped flag

#ifdef WIN32
    QueryPerformanceCounter(&endCount);
#else
    gettimeofday(&endCount, NULL);
#endif
}



///////////////////////////////////////////////////////////////////////////////
// compute elapsed time in micro-second resolution.
// other getElapsedTime will call this first, then convert to correspond resolution.
///////////////////////////////////////////////////////////////////////////////
double Timer::getElapsedTimeInMicroSec()
{
#ifdef WIN32
    if(!stopped)
        QueryPerformanceCounter(&endCount);

    startTimeInMicroSec = startCount.QuadPart * (1000000.0 / frequency.QuadPart);
    endTimeInMicroSec = endCount.QuadPart * (1000000.0 / frequency.QuadPart);
#else
    if(!stopped)
        gettimeofday(&endCount, NULL);

    startTimeInMicroSec = (startCount.tv_sec * 1000000.0) + startCount.tv_usec;
    endTimeInMicroSec = (endCount.tv_sec * 1000000.0) + endCount.tv_usec;
#endif

    return endTimeInMicroSec - startTimeInMicroSec;
}



///////////////////////////////////////////////////////////////////////////////
// divide elapsedTimeInMicroSec by 1000
///////////////////////////////////////////////////////////////////////////////
double Timer::getElapsedTimeInMilliSec()
{
    return this->getElapsedTimeInMicroSec() * 0.001;
}



///////////////////////////////////////////////////////////////////////////////
// divide elapsedTimeInMicroSec by 1000000
///////////////////////////////////////////////////////////////////////////////
double Timer::getElapsedTimeInSec()
{
    return this->getElapsedTimeInMicroSec() * 0.000001;
}



///////////////////////////////////////////////////////////////////////////////
// same as getElapsedTimeInSec()
///////////////////////////////////////////////////////////////////////////////
double Timer::getElapsedTime()
{
    return this->getElapsedTimeInSec();
}
Dan
  • 1,466
  • 1
  • 13
  • 27
  • @cha0site ups, sorry.. Well I guess it's trivial to port it to C. Hopefully will give an idea of how to do it to the author of the question. – Dan Jul 05 '12 at 16:39
0
#include <stdio.h>
#include <time.h>

int main()
{
clock_t start, finish;

start = clock();
....
finish = clock();   

printf("Time: %d", ((double) (finish - start)) / CLOCKS_PER_SEC);
return 0;
}

clock() gets the number of clock ticks since the start of the process. So subtracting start from finish and dividing by CLOCKS_PER_SEC should give you your running time in seconds. (For more info see the manual.

MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
0

Look at GetTickCount windows api, and About Timers (for Windows)

slashmais
  • 7,069
  • 9
  • 54
  • 80