clock()函數(shù)在C++中的使用示例有哪些

c++
小樊
82
2024-08-17 21:50:39
欄目: 編程語言

  1. 計(jì)算程序運(yùn)行時(shí)間
#include <iostream>
#include <ctime>

int main() {
    clock_t start, end;
    start = clock();
    
    // 執(zhí)行需要計(jì)時(shí)的代碼
    
    end = clock();
    double duration = double(end - start) / CLOCKS_PER_SEC;
    
    std::cout << "程序運(yùn)行時(shí)間:" << duration << "秒" << std::endl;
    
    return 0;
}
  1. 計(jì)算函數(shù)執(zhí)行時(shí)間
#include <iostream>
#include <ctime>

void func() {
    clock_t start, end;
    start = clock();
    
    // 執(zhí)行需要計(jì)時(shí)的代碼
    
    end = clock();
    double duration = double(end - start) / CLOCKS_PER_SEC;
    
    std::cout << "函數(shù)執(zhí)行時(shí)間:" << duration << "秒" << std::endl;
}

int main() {
    func();
    
    return 0;
}
  1. 計(jì)算兩個(gè)操作之間的時(shí)間間隔
#include <iostream>
#include <ctime>

int main() {
    clock_t start, end;
    start = clock();
    
    // 執(zhí)行操作1
    
    end = clock();
    double duration1 = double(end - start) / CLOCKS_PER_SEC;
    
    start = clock();
    
    // 執(zhí)行操作2
    
    end = clock();
    double duration2 = double(end - start) / CLOCKS_PER_SEC;
    
    std::cout << "操作1執(zhí)行時(shí)間:" << duration1 << "秒" << std::endl;
    std::cout << "操作2執(zhí)行時(shí)間:" << duration2 << "秒" << std::endl;
    
    return 0;
}

0