代码之家  ›  专栏  ›  技术社区  ›  SomeUser

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

  •  5
  • SomeUser  · 技术社区  · 17 年前

    这将显示多少秒:

    #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;
    }
    

    这将显示多少刻度:

    #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;
    }
    

    如何获得毫秒数?

    6 回复  |  直到 7 年前
        1
  •  11
  •   Community Mohan Dere    9 年前

    参考问题” Convert Difference between 2 times into Milliseconds “堆栈溢出时。

    或使用此:

    static double diffclock(clock_t clock1,clock_t clock2)
    {
        double diffticks=clock1-clock2;
        double diffms=(diffticks)/(CLOCKS_PER_SEC/1000);
        return diffms;
    }
    
        2
  •  6
  •   Peter Mortensen Pieter Jan Bonestroo    17 年前

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

    time call-program
    

    time命令乘以执行任何命令行所需的时间,并将其报告给您。

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

        3
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    17 年前

    有一个 CLOCKS_PER_SEC 宏帮助您将刻度转换为毫秒。

    有O/S特定的API来获取高分辨率计时器。

    您可以多次运行您的程序(例如1000次),并使用低分辨率计时器(例如一些秒数)测量,然后将该总数除以您运行该程序的次数,得到(较高分辨率)的平均时间。

        4
  •  2
  •   JRL    17 年前

    在Windows中,您可以使用 GetTickCount ,以毫秒为单位。

        5
  •  1
  •   Cat Plus Plus    17 年前

    在win32下,您可以使用 QueryPerformanceFrequency 和 QueryPerformanceCounter (我认为应该优先考虑,可能会退缩到 GetTickCount )您可以在msdn的社区内容部分找到这个例子。

        6
  •  0
  •   Josua Robson    7 年前

    这将显示多少刻度:

    #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;
    }
    

    如何获得毫秒数?

    clock() 返回毫秒。编译这个代码,它将返回1000。当然,如果您在Linux上而不是在Windows上替换 #include <windows.h> 具有 #include <unistd.h> 替代 Sleep(1000) 具有 usleep(1000000) .

    #include <stdio.h>
    #include <time.h>
    #include <windows.h>
    
    int main()
    {
        unsigned long x = clock();
        Sleep(1000);
        printf("Difference: %d", clock() - x);
    }