Hi everyone,
I am trying to make a program that times how long it runs for in seconds or milliseconds or whatever. The unit of time doesn't matter, I just need to know if C has any function I could use to do this. So, just as an example, I'm counting to 10,000 in a loop, and when it reaches 10,000 it stops and prints out the time it took to do. Would that be possible? Any links or snippets of code would be really appreciated. Thanks

This is just an additional thought but could I get the system time in seconds from the Epoch? So then I could do something like this:

for(conditions)
int x, y, timetaken;
x = (get the time for right now);
...more condions...
y = (get the time for right now);
timetaken= y-x;
...rest of code...

Can anyone give me some suggestions? Thanks

Take the initial time with time() , use inside a loop take the time again, then use difftime() to check the diffrence between the two; if it's greater than the max time, break the loop.

Here's a useful link

Thanks both of you for your help.
Here's the code I came up with. Its not perfect obviously but it lets the user pick a number to loop to and shows how long it takes to do that loop in seconds.

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

int main ()
{
  time_t start, endtime;
  unsigned long choice;
  unsigned long t;
  int difference;
  start = time(NULL);
  printf ("%ld seconds have passed since January 1, "
          "1970(Otherwise known as the Epoch)\n\nPlease enter the "
          "number to loop to: ", start);
  scanf("%ld", &choice);
  for(t = 0; t<choice; t++)     
        endtime=time(NULL);
  difference = difftime(endtime, start);
  printf("\n\nThe count to %ld took %d seconds!",t, 
          difference);
  
  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.