1

I'm writing code to time a for loop, and I used code given to me by my professor, and it uses system_clock. My problem is that on one of my for loops that I am timing, it is returning a negative time. Sometimes it's different number, but always negative.

Here's the code:

std::chrono::time_point<std::chrono::system_clock> start2, end2;
int sum2 = 0;
std::cout << "Sum on reference ";
start2 = std::chrono::system_clock::now();
for(int i = 0; i < 10000; i++)
{
    sum2 = secondSum(dr);
}
end2 - std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds2 = end2 - start2;
std::cout << "sum: " << sum2 << std::endl;
std::cout << "Elapsed time for data processing on reference: " << elapsed_seconds2.count() << "s\n";

Where dr is a reference to a struct with a filled array inside and secondSum is a function that sums different values inside that array.

Cheyanne
  • 13
  • 4
  • 2
    You don't instantiate "end2". "end2 - std::chrono::system_clock::now()" doesn't do anything but subtract and throw away the result. You probably meant to use "=" instead of "-". – Millie Smith Apr 06 '17 at 03:13
  • 1
    (1) Check compiler warnings. Your compiler should have told you `end2` is uninitialised. (2) Use your debugger. You should have noticed strange values for `end2` when calculating `elapsed_seconds` (it could even be zero in some cases). Then stepping over the line that was ***supposed to*** set `end2`, you'd notice it's unchanged. – Disillusioned Apr 06 '17 at 03:23

1 Answers1

0

You need to change the line end2 - std::chrono::system_clock::now(); to end2 = std::chrono::system_clock::now();. After that your code should work exactly how you intended it to work.

Andria
  • 4,712
  • 2
  • 22
  • 38