-8

I want to find out how much time a C/C++ program takes to produce output for a certain input file.

Usually, I make an input file in txt or other format and then produce an output file in txt or any other format. For example:

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

    //take input and give output

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

    return 0;
}

I run the program and it shows execution time on the console window. But I am not sure that if this is the most accurate way to know the execution time.

I need to know the execution time of a program for a certain input file to set the time limit for a programming problem in some school level programming contest.

halfer
  • 19,471
  • 17
  • 87
  • 173

3 Answers3

2

On Linux you can use the time command. Write time yourexecutable On windows you can use the powershell command Measure-Command {yourexecutable}. Replace yourexecutable with the actual program binary.

mdatsev
  • 2,886
  • 10
  • 25
1

In C you can use the time() function to measure the speed of a specific part of your program, for example:

# 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;
}

I have no idea how to do this in CPP...

ft_error
  • 132
  • 1
  • 6
  • Could anyone explain why the downvote? I don't think my answer is wrong, obviously it doesn't say how to do for CPP but others answered it. – ft_error Dec 30 '17 at 19:04
  • I'm guessing perhaps the downvote might have been from some C++ bigot? It seems a perfectly good answer to me... – paulsm4 Dec 31 '17 at 06:48
0

Surround the code of interest in a std::chrono saving the start time and then subtract the time at the end to get the duration.

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

You can then figure out how long to give the entry program and compare the duration against that time. Somewhat harder to forcefully abort the entry, that would pretty much require a wrapper program that launches the entries as separate processes (which is not a bad idea anyway) and if it timeout kill the process.

SoronelHaetir
  • 12,547
  • 1
  • 11
  • 21