C++调试代码常用技巧

1.输出程序运行时间

#include <ctime>    // 放在开头
    printf("Time used = %.3fs.
", (double)clock() / CLOCKS_PER_SEC);    // 放在需要输出已运行时间的地方

 2.生成随机数据

定义random(int n)函数生成随机数:

#include <cstdlib>
#include <ctime>

int random(int n){
    return (long long) rand() * rand() % n;
}

int main(){
    srand((unsigned)time(0));
    // 调用random(n)可返回0~n-1范围内的随机数
    // 如random(RAND_MAX)在Windows下随机返回0~32767-1内的数值

    return 0;
}

 在此基础上可以随机生成整数序列,区间列,树,图.具体实现见<<指南>> P440.

3.输入输出到文件

使用重定向:

freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);

VScode代码片段:

{
    "Print to console": {
        "scope": "cpp",
        "prefix": "qFI",
        "body": [
            "freopen("in.txt", "r", stdin);",
        ],
        "description": "A cpp freopen in template."
    }
}
CppIn.code-snippets
{
    "Print to console": {
        "scope": "cpp",
        "prefix": "qFO",
        "body": [
            "freopen("out.txt", "w", stdout);",
        ],
        "description": "A cpp freopen out template."
    }
}
CppOut.code-snippets

 4.手动开启O2

#pragma GCC optimize(2)
原文地址:https://www.cnblogs.com/Gaomez/p/14221786.html