找出C / C ++程序的运行时间

时间:2017-12-30 18:41:31

标签: c++ c

我想知道C / C ++程序为特定输入文件生成输出所花费的时间。

通常,我以txt或其他格式制作输入文件,然后以txt或任何其他格式生成输出文件。 例如:

int main()
{
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);

    //take input and give output

    //fclose(stdin);
    //fclose(stdout);

    return 0;
}

我运行程序,它在控制台窗口显示执行时间。但我不确定这是否是了解执行时间的最准确方法。

我需要知道某个输入文件的程序执行时间,以便在某些学校级别的编程竞赛中设置编程问题的时间限制。

3 个答案:

答案 0 :(得分:2)

在Linux上,您可以使用time命令。写time yourexecutable在Windows上,您可以使用powershell命令Measure-Command {yourexecutable}。将 yourexecutable 替换为实际的程序二进制文件。

答案 1 :(得分:0)

在C中,您可以使用time()函数来测量程序特定部分的速度,例如:

# include <time.h>
int main() {
    /* Do stuff here */
    time_t start, finish;
    time(&start);    /* time() stores the value in the pointed buffer */
    /* Measure this part */
    time(&finish);
    printf("Part 1 took %li seconds\n", finish - start);
    /* %li may not be the good flag according to your system. */
    /* Do extra stuff here */
    return 0;
}

我不知道如何在CPP中做到这一点......

答案 2 :(得分:-1)

将std :: chrono中感兴趣的代码包围起来,保存开始时间,然后减去结束时间以获得持续时间。

auto startTime = std::system_clock::now();
/* test code */
auto dur = std::system_clock::now() - startTime;
std::cout << "Duration: " << dur << std::endl;

然后,您可以计算出进入程序的时间长度,并将持续时间与该时间进行比较。强行中止条目有点困难,这几乎需要一个包装程序,它将条目作为单独的进程启动(无论如何都不是坏主意),如果超时则终止进程。