C/C++ 计算算法的执行时间

C/C++中,计算算法时间方法各异,不同系统平台提供系统调用接口可能不一样。

使用clock()

clock()获取从程序启动到调用时,CPU计时时间,精度CLOCKS_PER_SEC。
CLOCKS_PER_SEC也是每个CPU计数所代表的时间含义,比如CLOCKS_PER_SEC为1000,代表CPU每秒钟计数1000,即这段时间对应“时钟脉冲数”,clock() / CLOCKS_PER_SEC 就是这段时间的秒数。

遵循标准

POSIX.1-2001, POSIX.1-2008, C89, C99. XSI requires that
CLOCKS_PER_SEC equals 1000000 independent of the actual
resolution.

函数详解参见 man 3 clock手册

下面3个测试用例,分别让进程休眠2s,20ms,20us,然后统计进程运行时间。

#include <time.h>
#include <thread>

using namespace std;
using namespace std::this_thread::sleep_for;

void test_clock1()
{
    clock_t start = clock();
    sleep_for(chrono::seconds(2)); // 休眠2s
    clock_t end = clock();

    cout << double(start - end) / CLOCKS_PER_SEC << "s" << endl; // 打印2s
}

void test_clock2()
{
    clock_t start = clock();
    sleep_for(chrono::milliseconds(20)); // 休眠20ms
    clock_t end = clock();

    cout << double(start - end) / CLOCKS_PER_SEC << "s" << endl; // 打印0.02s
}

void test_clock3()
{
    // 测试用例3
    clock_t start = clock();
    sleep_for(chrono::microseconds(20)); // 休眠20us
    clock_t end = clock();

    cout << double(start - end) / CLOCKS_PER_SEC << "s" << endl; // 打印0.001s
}

可以看出,使用clock()方式无法获取 <= 1ms的时间。这是因为测试机上CLOCKS_PER_SEC=1000,也就是该计数器每秒计数1000次(时钟脉冲)。

使用time()

time() 返回自UTC时间(1970-01-01 00:00:00 +0000 (UTC))以来的秒数。精度为1秒。

遵循标准

SVr4, 4.3BSD, C89, C99, POSIX.1-2001. POSIX does not specify any
error conditions.

函数详见man 2 time手册

下面3个测试用例,分别让进程休眠2s,20ms,20us,然后统计进程运行时间。

void test_time1()
{
    time_t start = time(NULL);

    sleep_for(chrono::seconds(2)); // 打印2秒
    time_t end = time(NULL);

    cout << end - start << "s" << endl;
}

void test_time2()
{
    time_t start = time(NULL);

    sleep_for(chrono::milliseconds(20)); // 打印0秒
    time_t end = time(NULL);

    cout << end - start << "s" << endl;
}

void test_time3()
{
    time_t start = time(NULL);

    sleep_for(chrono::microseconds(20)); // 打印0秒
    time_t end = time(NULL);

    cout << end - start << "s" << endl;
}

原文链接: https://www.cnblogs.com/fortunely/p/15648465.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C/C++ 计算算法的执行时间

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/402819

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月21日 上午11:14
下一篇 2023年4月21日 上午11:14

相关推荐