繁体   English   中英

在C中查找一段代码的运行时

[英]Finding the runtime of a segment of code in C

下面的代码应该找到for循环的运行时间(以秒为单位)。 综观其他资源本应该做的伎俩,具有初始clock()从subracted clock()用于循环运行后。 任何想法为什么代码不能像写的那样工作?

#include <stdio.h>
#include <time.h>

//prototypes
int rfact(int n);
int temp = 0;

main()
{
    int n = 0;
    int i = 0;
    double result = 0.0;
    clock_t t;
    printf("Enter a value for n: ");
    scanf("%i", &n);

    printf("n=%i\n", n);

    //get current time
    t = clock();

    //process factorial 2 million times
    for(i=0; i<2000000; i++)
    {
        rfact(n);
    }

    printf("n=%i\n", n);

    //get total time spent in the loop
    result = (double)((clock() - t)/CLOCKS_PER_SEC);

    //print result
    printf("runtime=%d\n", result);
}

//factorial calculation
int rfact(int n)
{

    if (n<=0)
    {
        return 1;
    }
    return n * rfact(n-1);
}
result = (double)((clock() - t)/CLOCKS_PER_SEC);

这应该是:

result = ((double)(clock() - t))/CLOCKS_PER_SEC;

否则,你正在进行整数除法并将结果转换为double,这不是你想要的。

也:

printf("runtime=%d\n", result);

应该:

printf("runtime=%f\n", result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM