Run the 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)
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);

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.