我想检查我的函数在 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
定义是一样的,老师给了我它的来源,我只在这里使用它)。
EDIT:
Edited while
循环但结果仍然相同:
do
{
fun(a,b,c);
iterations++;
}while(get_wall_time() < wall0+seconds);
EDIT:
像这样的东西? :
#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;
}