我的代码的时间一直显示需要0秒

时间:2016-01-10 22:30:39

标签: c visual-studio-2013 time

我做错了什么?当我看到5,10,15,20等n时,我试图计算这个程序的时间,但是一切都回来了,花了0秒。我使用的是visual studio 2013。

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

int main()
{
clock_t start_t, end_t, total_t;
int n, first = 0, second = 1, next, c;

printf("Enter the number of terms\n");
scanf_s("%d", &n);

start_t = clock();
printf("First %d terms of Fibonacci series are :-\n", n);

for (c = 0; c < n; c++)
{
    if (c <= 1)
        next = c;
    else
    {
        next = first + second;
        first = second;
        second = next;
    }
    printf("%d\n", next);
}
end_t = clock();
total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("Total time taken by CPU: %f\n", total_t);
int  num;
scanf_s("%d", &num);

return 0;

}

3 个答案:

答案 0 :(得分:3)

变量total_t应为double:

double total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("Total time taken by CPU: %lf\n", total_t);

(带后缀_t的命名变量是一个非常糟糕的主意。)

除非您计算需要花费大量时间,至少10-16毫秒,否则clock()将不会记录任何更改,因为它的粒度相对较高。

答案 1 :(得分:0)

如果您的代码相对于您可用的时钟的粒度花费了少量时间,您可以多次运行它然后除以。

s = timer()
for ( times = 0; times < n; ++times) {
    dothing();
}
e = timer();
print (e-s)/n;

你需要担心的一件事是优化器过于聪明并且优化了循环(如果dothing()没有外部副作用,那么根本就没有理由这样做,更不用说数千次了。所以没有任何东西可以返回一些价值并在最后打印出这个价值。

x = 0
s = timer()
for ( times = 0; times < n; ++times) {
    x ^= dothing();
}
e = timer();
print (e-s)/n;
print x;

答案 2 :(得分:0)

纠正编译错误后:

编译时始终启用所有警告:

总是尝试编写可能需要此行位于文件顶部的可移植代码:

#define _CRT_SECURE_NO_WARNINGS

遵循公理:每行只有一个语句,并且(最多)每个语句一个变量声明

通常,为类型声明保留_t后缀。

使用便携式方法清洁标准输入,然后等待用户按下击键

以下代码是结果:

#define _CRT_SECURE_NO_WARNINGS

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

int main()
{
    clock_t start;
    clock_t end;
    double total;

    int n;
    int first  = 0;
    int second = 1;
    int next;
    int c;

    printf("Enter the number of terms\n");
    scanf("%d", &n);

    start = clock();
    printf("First %d terms of Fibonacci series are :-\n", n);

    printf("%d\n", 0);
    printf("%d\n", 1);

    for (c = 2; c < n; c++)
    {
        next = first + second;
        first = second;
        second = next;

        printf("%d\n", next);
    }

    end = clock();

    total = (double)(end - start) / CLOCKS_PER_SEC;
    printf("Total time taken by CPU: %f\n", total);

    int ch;
    while( (ch = getchar()) != EOF && '\n' != ch );
    getchar();

    return 0;
}

以下是示例输出:

Enter the number of terms
10
First 10 terms of Fibonacci series are :-
0
1
1
2
3
5
8
13
21
34
Total time taken by CPU: 0.000043