gpt4 book ai didi

c - 如何查看某个函数以 3 秒的间隔被调用了多少次?

转载 作者:行者123 更新时间:2023-12-02 21:56:40 26 4
gpt4 key购买 nike

我想检查我的函数在 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;
}

最佳答案

将 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);

关于c - 如何查看某个函数以 3 秒的间隔被调用了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17659867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com