简体   繁体   中英

Keeping track as to how long a program ran for in C

How can I keep track of how long my program executed a certain instruction in, for example, if one were to measure the diskusage, that would take time, and at the end my program should give an oupit along the lines of

real=50.0s user=30.s sys=20.0s

How do I distinguish and gather the system time, and the actual command time?

Back in the day I used to use pureCoverage to examine the execution time, but it was expensive. There might be free tools that do the same sort of thing, but for a quick and dirty solution...

include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
  time_t start_time, end_time;
  start_time = time(NULL);
  //Do your thing...
  end_time  = time(NULL);

  int diff = end_time - start_time;
  //Diff will be the number of milliseconds that elapsed.
}

Use getrusage in Linux:

#include <sys/time.h>
#include <sys/resource.h>

...

struct rusage rusage;

getrusage(RUSAGE_SELF, &rusage);
/* use rusage.ru_utime and rusage.ru_stime for user and system time resp. */

There's another solution, not much different from the previous example.

#include<time.h>
int main ()
{
    clock_t start_time, stop_time;

    start_time = clock();

    // ... do your thing;

    stop_time = clock();

    printf("Elapsed time: %lf", (double)( stop_time - start_time ) / CLOCKS_PER_SEC);
}

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