如何检查函数被调用多少次了3间隔(秒)? [英] How can I check how many times a function was called with a 3 seconds interval?
问题描述
我想检查多少次,我的功能,可以在3秒内运行。我写了code:
的#include<&string.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&time.h中GT;
#包括LT&; SYS / time.h中>
#包括LT&; SYS / RESOURCE.H>双get_wall_time(){
timeval结构的时间;
如果(函数gettimeofday(安培;时间,NULL)){
//处理错误
返回0;
}
回报(双)time.tv_sec +(双)time.tv_usec * .000001;
}INT主(INT ARGC,字符** argv的)
{
长迭代= 0;
双秒= 3.0; 双wall0 = get_wall_time(),现; 做
{
有趣(A,B,C);
现在= get_wall_time();
迭代++;
}而(现< wall0 +秒); 的printf(%鲁\\ n,迭代); 返回0;
}
但东西告诉我它不是好的在所有...我比较了从我的老师一个可执行的成果,原来,他的节目的确比同,3秒的时间间隔矿(乐趣
的定义是相同的,老师给了我它的来源,我只在这里使用它)。
编辑:
编辑,而
循环,但结果还是一样的:
做
{
有趣(A,B,C);
迭代++;
}而(get_wall_time()< wall0 +秒);
编辑:
这样的事情?
的#include<&stdlib.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&signal.h中GT;
#包括LT&;&unistd.h中GT;/ * 3秒*的/
挥发性INT秒= 3;无效手柄(INT SIG){
--seconds;
报警(1);
}诠释的main()
{ 信号(SIGALRM,手柄);
报警(1); 而(秒)
{
有趣(A,B,C);
迭代++;
} 的printf(%鲁\\ n,迭代); 返回0;
}
结束语有gettimeofday在功能会增加你越来越少的迭代。比你的教授。你真的应该这样做:
timeval结构开始,结束;做{
函数gettimeofday(安培;启动,NULL);
有趣(A,B,C);
函数gettimeofday(安培;最后,NULL);
迭代++;
现在=(end.tv_sec - start.tv_sec)/1000.0;
现在+ =(end.tv_usec - start.tv_usec)* 1000.0;
}而(现< 3000);
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;
}
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);
这篇关于如何检查函数被调用多少次了3间隔(秒)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!