I wanted to know the execution time of a program, but I also wanted to exclude the time needed for file input/output. For this purpose I used the time() function. There are many .h and .cpp files but here are the only places where time objects are referenced.
My problem is, while start’s value is set correctly at the beginning it loses it (is set to zero) when dosomethingelse() is invoked for the first time. This makes sub_duration to have a very big value because now the difference between end and start , which is zero, is the value of end.
Here is how I used it:
main.cpp
time_t start=0;
time_t end=0;
time_t sub_duration=0;
time_t total_duration=0;
int main()
{
start = time(NULL);
while(somethingtodo)
{
dosomething();
dosomethingelse();
}
end = time(NULL);
sub_duration = difftime(end,start);
total_duration += sub_duration;
}
dosth.h
extern time_t start;
extern time_t end;
extern time_t sub_duration;
extern time_t total_duration;
dosomethingelse();
dosth.cpp
#include"dosth.h"
dosomethingelse()
{
if(somecondition)
{
end = time(NULL);
sub_duration = difftime(end,start);
total_duration += sub_duration;
writesomethingTofile();
start = time(NULL);
}
}
The problem is that
startandendare global… when you set them insidedosomethingelse(), you’re re-setting thestartfor the whole program.The solution is to keep a local timer inside
dosomethingelse(), and subtract the time spent in that function from the total.