关于winapi:C程序输出分析

C program output analysis

在Windows 10上运行的简单C程序。(Visual Studio 2013)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <time.h>

void hello(){
    printf("hello world");
}

int _tmain(int argc, _TCHAR* argv[])
{
    clock_t t;
    for (int i = 0; i<50; i++){
        t = clock();
        hello();
        t = clock() - t;
        double time_taken = ((double)t) / CLOCKS_PER_SEC; // in seconds

        printf("hello() took %f ms to execute \
"
, time_taken * 1000);
    }
    getchar();
    return 0;
}

输出:

1
2
3
4
5
6
7
8
9
hello worldhello() took 0.000000 ms to execute(35times)
hello worldhello() took 17.000000 ms to execute
hello worldhello() took 3.000000 ms to execute
hello worldhello() took 2.000000 ms to execute
hello worldhello() took 0.000000 ms to execute(5 times)
hello worldhello() took 15.000000 ms to execute
hello worldhello() took 0.000000 ms to execute(4 times)
hello worldhello() took 16.000000 ms to execute
hello worldhello() took 0.000000 ms to execute

某些行为0.000000,某些行为15.000000-17.000000

这些输出可能与第二次运行的输出不完全相同。但是在第二/第三次..运行中,必须有一些行包含0.000000ms和15.000000-17.000000ms。

  • 0ms到16ms(是否是进程CPU时间?)。请您解释一下真正的原因是什么。

  • 如果我想避免这种更改并获得0-1 ms之类的统一输出,那么我该如何更改我的代码。 (循环运行了50次,但是如果我运行100次或1000次,则时间效果很容易理解。)


  • 您的代码太短,并且clock()没有精确测量执行时间所需的精度。添加系统开销来执行时钟测量,您将获得随机结果。

    要获得更好的度量,请在函数上循环一百万次,然后计时


    n


    n