How can I check how many times a function was called with a 3 seconds interval?

空扰寡人 提交于 2019-12-24 01:56:19

问题


I would like to check how many times my function can be run in 3 seconds. I wrote that code:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>

double get_wall_time(){
    struct timeval time;
    if (gettimeofday(&time,NULL)){
        //  Handle error
        return 0;
    }
    return (double)time.tv_sec + (double)time.tv_usec * .000001;
}

int main(int argc, char **argv)
{
    long iterations = 0;
    double seconds = 3.0;

    double wall0 = get_wall_time(), now;

    do
    {
        fun(a,b,c);
        now = get_wall_time();
        iterations++;
    }while(now < wall0+seconds);

    printf("%lu\n", iterations);

    return 0;
}

But something tells me its not ok at all... I compared results with an executable from my teacher and turned out that his program does more iterations than mine in the same, 3-seconds time interval (fun is defined the same, teacher gave me its source, I only use it here).

EDIT:

Edited while loop but results still the same:

        do
        {
            fun(a,b,c);
            iterations++;
        }while(get_wall_time() < wall0+seconds);

EDIT:

something like this? :

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

/* 3 seconds */
volatile int seconds = 3;

void handle(int sig) {
    --seconds;
    alarm(1);
}

int main()
{

    signal(SIGALRM, handle);
    alarm(1);

    while(seconds)
    {
        fun(a,b,c);
        iterations++;
    }

    printf("%lu\n", iterations);

    return 0;
}

回答1:


Wrapping the gettimeofday in a function will add to you getting less iterations. Than your professor. You should really be doing this:

struct timeval start, end;

do{
  gettimeofday(&start,NULL);
  fun(a,b,c);
  gettimeofday(&end,NULL);
  iterations++;
  now =  (end.tv_sec - start.tv_sec)/1000.0;
  now += (end.tv_usec - start.tv_usec)*1000.0;
}while(now < 3000);



回答2:


you can use a thread to wait for 3sec.

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

char flag = 0;

void * timer(void *param)
{
  sleep(3);
  flag = 1;
  return (0);
}


int main()
{
  int   count = 0;
  pthread_t     tid;

  pthread_create(&tid, NULL, timer, NULL);
  while (flag == 0)
    {
      fun(a,b,c);
      count++;
    }
  printf("%i\n", count);
}

and compile with the library pthread -lpthread with gcc

I avoid gettimeofday() because a syscall is quite costly.



来源:https://stackoverflow.com/questions/17659867/how-can-i-check-how-many-times-a-function-was-called-with-a-3-seconds-interval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!