温馨提示×

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

c++
小樊
82
2024-08-17 21:50:39
栏目: 编程语言

  1. 计算程序运行时间
#include <iostream>
#include <ctime>

int main() {
    clock_t start, end;
    start = clock();
    
    // 执行需要计时的代码
    
    end = clock();
    double duration = double(end - start) / CLOCKS_PER_SEC;
    
    std::cout << "程序运行时间:" << duration << "秒" << std::endl;
    
    return 0;
}
  1. 计算函数执行时间
#include <iostream>
#include <ctime>

void func() {
    clock_t start, end;
    start = clock();
    
    // 执行需要计时的代码
    
    end = clock();
    double duration = double(end - start) / CLOCKS_PER_SEC;
    
    std::cout << "函数执行时间:" << duration << "秒" << std::endl;
}

int main() {
    func();
    
    return 0;
}
  1. 计算两个操作之间的时间间隔
#include <iostream>
#include <ctime>

int main() {
    clock_t start, end;
    start = clock();
    
    // 执行操作1
    
    end = clock();
    double duration1 = double(end - start) / CLOCKS_PER_SEC;
    
    start = clock();
    
    // 执行操作2
    
    end = clock();
    double duration2 = double(end - start) / CLOCKS_PER_SEC;
    
    std::cout << "操作1执行时间:" << duration1 << "秒" << std::endl;
    std::cout << "操作2执行时间:" << duration2 << "秒" << std::endl;
    
    return 0;
}

0