如何计算程序运行需要多少毫秒?

新手上路,请多包涵

这将显示多少秒:

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

我如何获得毫秒?

原文由 SomeUser 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

请参阅 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;
}

原文由 Satbir 发布,翻译遵循 CC BY-SA 3.0 许可协议

下面的 C++ 程序以毫秒、微秒、纳秒和秒为单位计算简单代码所用的时间。它包括 <chrono.h> 标头,它使用 system_clock() 提供对当前时间的访问。 system_clock() 旨在表示实时并由系统上运行的所有进程使用。

代码:

 #include <iostream>
#include <chrono>
#include <unistd.h>

using namespace std;

int main() {
    auto start = chrono::steady_clock::now();

    sleep(2);

    auto end = chrono::steady_clock::now();

    cout << "Elapsed time in microseconds: "
         << chrono::duration_cast<chrono::microseconds>(end - start).count()
         << " µs" << endl;

    cout << "Elapsed time in milliseconds: "
         << chrono::duration_cast<chrono::milliseconds>(end - start).count()
         << " ms" << endl;

    cout << "Elapsed time in nanoseconds: "
         << chrono::duration_cast<chrono::nanoseconds>(end - start).count()
         << " ns" << endl;

    cout << "Elapsed time in seconds: "
         << chrono::duration_cast<chrono::seconds>(end - start).count()
         << " sec";

    return 0;
}

输出:

 Elapsed time in microseconds: 2000127 µs
Elapsed time in milliseconds: 2000 ms
Elapsed time in nanoseconds: 2000127736 ns
Elapsed time in seconds: 2 sec

原文由 Rajiv Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题