2013-07-15 25 views
1

我想检查我的功能可以在3秒内运行多少次。我写的代码:如何以3秒的时间间隔检查函数的调用次数?

#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; 
} 

但东西告诉我它不是好的在所有...我比较了从我的老师一个可执行的成果,原来,他的节目做更多的迭代比我同在,3-秒的时间间隔(fun定义相同,老师给我它的来源,我只在这里使用它)。

编辑:

编辑while循环,但结果还是一样:

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

编辑:

这样的事情? :

#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

你的代码不只是测量你的函数在3秒内被调用的次数。你正在测量你可以调用你的函数的次数和get_wall_time。 – hatchet

+0

@hatchet:好的,把我的'while'改成'} while(get_wall_time() yak

+1

对于函数的每次执行,仍然会调用get_wall_time。 – hatchet

回答

4

在函数中包装gettimeofday会增加迭代次数。比你的教授。你应该这样做:

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); 
+0

如果有趣的(a,b,c)执行时间非常短,这仍然可能导致大量的时间花费在计算电话时间的开销上。 – hatchet

1

你可以使用一个线程等待3秒。

#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); 
} 

,并与库编译并行线程-lpthread用gcc

我的gettimeofday避免(),因为系统调用是相当昂贵的。

相关问题