我如何计算程序运行所需的毫秒数?

Som*_*ser 6 c++ timer

这将显示多少秒:

#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
    int times,timed;

    times=time(NULL);
    //CODE HERE

    timed=time(NULL);
    times=timed-times;
    cout << "time from start to end" << times;
}
Run Code Online (Sandbox Code Playgroud)

这将显示多少个刻度:

#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
    int times,timed;

    times=clock();
    //CODE HERE

    timed=clock();
    times=timed-times;
    cout << "ticks from start to end" << times;
}
Run Code Online (Sandbox Code Playgroud)

我如何获得毫秒?

Sat*_*bir 13

请参阅Stack Overflow上的" 将差值转换为2毫秒到毫秒 " 之间的问题.

或者用这个:

static double diffclock(clock_t clock1,clock_t clock2)
{
    double diffticks=clock1-clock2;
    double diffms=(diffticks)/(CLOCKS_PER_SEC/1000);
    return diffms;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么使用(CLOCKS_PER_SEC / 1000)?CLOCKS_PER_SEC不是1000,所以CLOCKS_PER_SEC / 1000 = 1,除以1是没有意义的。 (2认同)

jpm*_*los 6

如果您使用Unix OS,如Linux或Mac OS X,则可以转到命令行并使用该行

time call-program
Run Code Online (Sandbox Code Playgroud)

time命令会计算任何命令行的执行时间,并向您报告.

我不知道是否有类似于Windows的东西,也不知道如何测量C/C++程序中的毫秒数.