首页 > 解决方案 > 测量 C 中函数所花费的时间总是 0.000000

问题描述

我阅读了geeksforgeeks的一篇文章。代码显示了一个测量时间函数成本的函数。

在我的机器上,无论我按多长时间,我总是得到 0.000000。

我打印 t = clock() - t; t 总是等于 0.00000,我将语句重写为这个,仍然得到 0.000000。

clock_t m;
m = clock() - t;

centos7中的gcc版本

[root@localhost log]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
/* Program to demonstrate time taken by function fun() */
#include <stdio.h> 
#include <time.h> 

// A function that terminates when enter key is pressed 
void fun() 
{ 
    printf("fun() starts \n"); 
    printf("Press enter to stop fun \n"); 
    while(1) 
    { 
        if (getchar()) 
            break; 
    } 
    printf("fun() ends \n"); 
} 

// The main program calls fun() and measures time taken by fun() 
int main() 
{ 
    // Calculate the time taken by fun() 
    clock_t t; 
    t = clock(); 
    fun(); 
    t = clock() - t; 
    double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds 

    printf("fun() took %f seconds to execute \n", time_taken); 
    return 0; 
} 

标签: c

解决方案


你好试试这个:

unsigned int t=time(0);
fun();
unsigned int result=time(0)-t; // result is the time taken by fun

推荐阅读