C/C++ 计算运行时间

C Style <ctime> & clock()

#include <iostream>
#include <cstdio>
#include <ctime>

using namespace std;

int main() {
    clock_t now = clock();
    freopen("/dev/null", "w", stdout);
    for (int i = 0; i < 1e9; i++) {
        putchar('0');
    }
    double s = (double)(clock() - now) / CLOCKS_PER_SEC ;
    cerr << s << endl;
    return 0;
}

C++11 <chrono>

#include <iostream>
#include <cstdio>
#include <chrono>

using namespace std;

int main() {
    chrono::steady_clock::time_point begin = chrono::steady_clock::now();
    freopen("/dev/null", "w", stdout);
    for (int i = 0; i < 1e9; i++) {
        putchar('0');
    }
    chrono::steady_clock::time_point end = chrono::steady_clock::now();
    double s = chrono::duration_cast<chrono::microseconds>(end - begin).count() / 1000000.0 ;
    cerr << "Time difference (sec) = " << s << endl;
    return 0;
}

Linux time command

time 是shell内置指令

/usr/bin/time 是系统内的一个可执行文件

一般用来计算时间的话都是足够的,time 可能有一些/usr/bin/time 不支持的功能。

 

CC BY-NC-SA 4.0 本作品使用基于以下许可授权:Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注