How to run your code for 2 CPU-seconds

From IridiaWiki
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Registering an alarm with SIGALRM allows to stop the execution after the specified amount of seconds (wall-clock time).

To stop after a given amount of CPU-seconds you should use SIGPROF.

Copy the following example in 'test.c':

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>

int run;

static void stop(int _)
{
    run = 0;
}

float do_something() {
    /* some random computation, this example comes from http://www.cplusplus.com/forum/beginner/1149/ */
    unsigned int decP;
    unsigned int denom=3;
    float ourPi=4.0f;
    int addFlop=1;
    int i = 1;

    run = 1;
    while (run) {
        if (addFlop) {
            ourPi -= (4.0/denom);
            addFlop = 0;
            denom += 2;
        } else {
            ourPi += (4.0/denom);
            addFlop = 1;
            denom += 2;
        }
        i++;
    }

    return ourPi;
}


int main(int argc, char *argv[])
{
    time_t t = time(NULL);
    struct itimerval timer;

    int max_time = 2; /* two seconds */

    timer.it_value.tv_sec = max_time;
    timer.it_value.tv_usec = 0;
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 0;

    signal(SIGPROF, stop);
    signal(SIGINT, stop);
    if (setitimer (ITIMER_PROF, &timer, NULL) != 0) {
        printf("error in setitimer\n");
        exit(10);
    }

    clock_t t1 = clock();
    float res = do_something();
    clock_t t2 = clock();

    printf("Result is %.12f.\n", res);
    printf("Simulation lasted %f CPU-seconds.\n", (((double)t2 - t1) / CLOCKS_PER_SEC));

    return 0;
}

Compilation and test:

$ make test
cc     test.c   -o test
$ ./test 
Result is 3.141596794128.
Simulation lasted 2.002495 CPU-seconds.