简体   繁体   中英

How can I measure time taken by a process in C using Linux System Call gettimeofday()?

I'm trying to find how much time the process / function took to find the solution. I am asked to do it using gettimeofday() Linux System Call. Any help? Thanks in advance.

Here is my tested code snipped:

struct timeval t1, t2;
double elapsedTime;

// start timer
gettimeofday(&t1, NULL);

// do something
// ...

// stop timer
gettimeofday(&t2, NULL);

// compute and print the elapsed time in millisec
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
fprintf(stderr, "elapsedTime = %5.3fms \n", elapsedTime);

Hope that helps.

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