Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code for exactly one second

I would like to know how I can program something so that my program runs as long as a second lasts.

I would like to evaluate parts of my code and see where the time is spend most so I am analyzing parts of it.

Here's the interesting part of my code :

int size = 256
clock_t start_benching = clock();
for (uint32_t i = 0;i < size; i+=4)
{
    myarray[i];
    myarray[i+1];
    myarray[i+2];
    myarray[i+3];
}
clock_t stop_benching = clock();

This just gives me how long the function needed to perform all the operations.

I want to run the code for one second and see how many operations have been done.

This is the line to print the time measurement:

printf("Walking through buffer took %f seconds\n", (double)(stop_benching - start_benching) / CLOCKS_PER_SEC);
like image 288
user3694354 Avatar asked Nov 22 '25 19:11

user3694354


2 Answers

A better approach to benchmarking is to know the % of time spent on each section of the code. Instead of making your code run for exactly 1 second, make stop_benchmarking - start_benchmarking the total run time - Take the time spent on any part of the code and divide by the total runtime to get a value between 0 and 1. Multiply this value by 100 and you have the % of time consumed at that specific section.

like image 86
Dennis C Furlaneto Avatar answered Nov 25 '25 10:11

Dennis C Furlaneto


Non-answer advice: Use an actual profiler to profile the performance of code sections.

On *nix you can set an alarm(2) with a signal handler that sets a global flag to indicate the elapsed time. The Windows API provides something similar with SetTimer.

#include <unistd.h>
#include <signal.h>

int time_elapsed = 0;

void alarm_handler(int signal) {
  time_elapsed = 1;
}

int main() {
  signal(SIGALRM, &alarm_handler);
  alarm(1); // set alarm time-out to 1 second

  do {
    // stuff...
  } while (!time_elapsed);

  return 0;
}

In more complicated cases you can use setitimer(2) instead of alarm(2), which lets you

  • use microsecond precision and
  • choose between counting
    • wall clock time,
    • user CPU time, or
    • user and system CPU time.
like image 42
David Foerster Avatar answered Nov 25 '25 09:11

David Foerster