terça-feira, 29 de novembro de 2011

Stress test in C !?

This code will create N threads that take B bytes of memory each and spin forever. Call it whihout arguments to see the usage.

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

#define pexit(s) ({perror(s); exit(EXIT_FAILURE);})

static unsigned int sleepi = 0;
void *xmalloc(size_t);
void *tfunction(void *);

int main(int argc, char **argv)
{
        int nthreads;
        int nbytes;
        int i;
        pthread_t *threadv;

        if (argc <= 2) {
                printf("Usage: %s NUMBER_OF_THREADS NUMBER_OF_BYTES_PER_THREAD "
                                "[SLEEP_INTERVAL_IN_SECS]\n", argv[0]);
                exit(EXIT_FAILURE);
        }

        nthreads        = atoi(argv[1]);
        nbytes          = atoi(argv[2]);
        if (argc > 3) {
                sleepi          = atoi(argv[3]);
        }

        threadv = xmalloc(sizeof(pthread_t) * nthreads);
        for (i = 0; i < nthreads; i++) {
               pthread_create(&threadv[i], NULL, tfunction, (void *)&nbytes);
        }
        while (1) sleep(~0lu); /* MAX LONG POSSIBLE */
        return 0;
}

void *xmalloc(size_t siz)
{
        void *n = malloc(siz);
        if (!n)
                pexit("malloc"); 
        return n;
}

void *tfunction(void *num)
{
        int i = *(int *)num;
        while (i--) malloc(1);
        if (sleepi)
                while (1) sleep(sleepi);
        else
                while (1);
}

Nenhum comentário:

Postar um comentário