Trouble with figuring out timing

Hey guys,

I'm diving into multithreading (or, at least, trying to) and wrote a function that would figure out how long some process took (see double diffClocks(...)):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <thread>
#include <ctime>

using std::cout;
using std::cin;

typedef unsigned int uint;
typedef void (*workerFunct)(const uint, const uint, int*);

double diffClocks(const clock_t start, const clock_t end);

int main(int argc, char* argv[]) {

	clock_t start = clock();

	uint x = 0;
	for(uint i = 0; i < 100000000; i++) {
		x += i;
	} // END for(i)

	clock_t end = clock();

	cout << diffClocks(start, end) << '\n';

return 0;
} // END int main()

double diffClocks(const clock_t start, const clock_t end) {
return ( (end - start) / CLOCKS_PER_SEC );
} // END double diffClocks() 


However, the call on line 24 (cout << diffClocks(start, end) << '\n';) always resolves to zero. Why is this?

Thanks for any input!
1
2
3
4
double diffClocks(const clock_t start, const clock_t end)
{
      return ((double)(end - start) / (double) CLOCKS_PER_SEC );
}


Using typecast.
clock_t is an integer. CLOCKS_PER_SEC is also an integer.

When you divide a(5000) by b(10000), one of two things may happen :
If they are floating numbers : 5000.0 / 10000.0 = 0.5
If they are integers : 5000 / 10000 = 0 (only quotient part is counted)
Worked perfectly thank you very much! For some reason I thought the typecasting would be implicit since the function returned a double...
For measuring the time (as in, the number of seconds) that a process takes, don't use clock – it provides the CPU time, or the number of CPU cycles. Dividing by CLOCKS_PER_SEC won't give entirely accurate results.

Prefer instead some of the functions from <chrono>:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <chrono>

// ...

int main() {
    using namespace std::chrono;
    auto start = steady_clock::now();

    // do work here

    auto end = steady_clock::now();
    double secs = duration_cast<duration<double>>(end - start).count();

    std::cout << "Time taken: " << secs << "\n";
    return 0;
}
Topic archived. No new replies allowed.