我想检查我的功能可以在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;
}
你的代码不只是测量你的函数在3秒内被调用的次数。你正在测量你可以调用你的函数的次数和get_wall_time。 – hatchet
@hatchet:好的,把我的'while'改成'} while(get_wall_time()
yak
对于函数的每次执行,仍然会调用get_wall_time。 – hatchet