zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    js图片轮换
    PHP如何打造一个高可用高性能的网站呢?
    php中浮点数计算问题
    jQuery ajax()使用serialize()提交form数据
    js最新手机号码、电话号码正则表达式
    swoole是如何实现任务定时自动化调度的?
    Facebook的“零售吸引力”,互联网营销 狼人:
    Google勇敢新世界,互联网营销 狼人:
    Facebook的成功之道,互联网营销 狼人:
    李彦宏分享百度危机中如何“弯道超车”,互联网营销 狼人:
  • 原文地址:https://www.cnblogs.com/fortunely/p/15648465.html
Copyright © 2011-2022 走看看