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

标签 c benchmarking

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

相关文章:

c - 在 Lex 中解析命令行参数

c - 使用标准输入和标准输出管道到相同的 c 程序

c - 通用结构的 token 粘贴

java - 有没有比较 PHP 和 JSP 的基准?

ruby-on-rails - 测试速度 : ActiveRecord use_transactional_fixtures vs. DatabaseCleaner.strategy = :transaction

c中两个数组的公共(public)数字函数

c - POSIX Pthread 两个数字相加 C 代码

MySQL 基准测试,预生产

c++ - 基准测试(python 与使用 BLAS 的 c++)和(numpy)

Java 与 PHP 基准测试