简体   繁体   中英

How to find how much time has elapsed in C++ using sys/times.h

I want to do something like the following:

get t1
run a program
get t2
display t2 - t1

Basically I'm trying to find out how much time a program used. I have seen several solutions to this, but the one I like is the one where sys/times.h is used, but haven't quite figured it out. How can this be done?

struct timeval timeStart,timeEnd;
int error1=gettimeofday(&timeStart, NULL);
//stuff you want to measure goes here
int error2=gettimeofday(&timeEnd, NULL);
if(error1 || error2) return -1; //some error occured

//this gives the result in microseconds.
return (timeEnd.tv_sec - timeStart.tv_sec)*1000000.0+(timeEnd.tv_usec - timeStart.tv_usec); 

You can also use, which is cross-platform (I don't know if that matters to you). It would be simple: you can use the clock() function, which returns an integer. There is a macro called CLOCKS_PER_SEC that tells you how many clock pulses there will be in 1 second in the current machine. In C code, that would be:

#include <time.h>

unsigned old_clock = clock();
unsigned current_clock = 0;//will be assigned later
//do anything you want to time
current_clock = clock();
printf("%d seconds (%d milliseconds) ellapsed.\n", (current_clock - old_clock) / CLOCKS_PER_SEC, (current_clock - old_clock) / (CLOCKS_PER_SEC / 1000) );

Try this..

#include <iostream>
#include <sys/times.h>
int main()
{
    time_t clkTimeBegin, clkTimeEnd;
    time(&clkTimeBegin);
    std::cout<<"Run your program here"<<std::endl;
    time(&clkTimeEnd);
    std::cout << "Time diff, " << difftime(clkTimeBegin, clkTimeEnd ) << "!\n"; 
}

If you're using windows, look into QueryPerformanceCounter and QueryPerformanceFrequency. They are available after you include windows.h

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM