| srbbff (7) | |
|
Hi all, I am trying to measure the CPU time of a program using clock(). But when it takes a certain amount of time to run the code, the time consumption becomes negative. From what I understand, the problem is, that clock wraps around every 2147 seconds (32 bit system with CLOCKS_PER_SECOND = 1000000). I assume I have to somehow count the cycles and add to my end variable, but I do not know how to do this... My code is clock_t start, end; double cpu_time_used; start = clock(); //DO A LOT OF STUFF end = clock(); cpu_time_used = (double) (end-start)/CLOCKS_PER_SECOND; And my problem is then, that cpu_time_used becomes negative for long runs. How do I fix this? | |
|
Last edited on
|
|
| Dragonster82 (12) | |
|
You can store it in multiple variables, then sum them all up for the end = clock part. for example: You create 3 variables: int nInt, int zInt, int cInt, ( Or any name you want, really. ) Then at your // Do alot of stuff Do this in the loop: if(cpu_time_used == about like 1 digit before the maximum you think you can handle) { nInt = cpu_time_used; cpu_time_used = 0; } if(nInt == same as above) { zInt = nInt; nInt = 0; } Then repeat for cInt. So basically it is splitting the sum to different variables so that the system is able to hold more. | |
|
|
|
| srbbff (7) | |
|
@Dragonster82: I have to apologize in advance for my stupidity, I am a very unexperienced programmer. But I have a couple of question regarding the approach: 1. My "Do a lot of stuff" is one big main method, where in this method should the if-statement be placed? cpu_time_used is not calculated until the end of the method, so how do I check the if-statement you suggest before it has in fact been calculated? From the method you suggest it seems that cpu_time_used is continuously kept track of... 2. How do I know the number "the maximum you think you can handle"? 3. Further, I thought it was the clock_t variables that could not hold enough room, not cpu_time_used, which is just the difference between start and end converted into seconds. Again, these are probably stupid questions, but I hope you have the patience to bear with me. | |
|
Last edited on
|
|
| naraku9333 (919) | |
| Maybe difftime can help in your situation. http://www.cplusplus.com/reference/clibrary/ctime/difftime/ | |
|
|
|
| ne555 (4039) | ||
|
time() and clock() measure different things. I would suggest to use
http://www.cplusplus.com/forum/unices/74547/#msg399434 | ||
|
|
||
| srbbff (7) | |
| But it is the CPU time I need, isn't that obtained by clock? | |
|
|
|
| ne555 (4039) | |
|
OK, in that case use getrusage() http://linux.die.net/man/2/getrusage (you want user time) Just call it at the end | |
|
|
|