1

I need a C program that would execute for a precise number of CPU seconds passed in as a parameter. I need such a program in order to test code that monitors a process' CPU usage.

Example:

busywait x

Should run for x seconds on my processor.

Will Brode
  • 1,026
  • 2
  • 10
  • 27

2 Answers2

1

This is the C program I wrote to solve my problem. It continuously checks the number of clock cycles until the correct number of processor-seconds has been used.

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

int main(int argc, char * argv[])
{
     clock_t start, end;
     double cpu_time_used;
     int wait;

     sscanf(argv[1], "%d", &wait);

     start = clock();
     end = clock();
     while (((double) (end - start)) / CLOCKS_PER_SEC < wait)
     {
          end = clock();
     }
}
Will Brode
  • 1,026
  • 2
  • 10
  • 27
-1

I think you can just type in sleep x in a shell where x is seconds. I only tested on bash on a Mac, but I believe other unixes should have the same thing.

Danny
  • 2,221
  • 2
  • 18
  • 21
  • So far as I can tell, the sleep command does not busy wait. I can't seem to find a definitive link to support my claim however. – Will Brode May 09 '13 at 22:21
  • Sleep ? By definition it's not a busy wait (well, sleeping might be "busy" in old ms-dos stuff by the way). I think the easier way to waste CPU cycle accomplishing nothing of value is to build your own "dirtysleep" program, go and consume CPU time :) – Pascail May 09 '13 at 22:39
  • Yeah I looked around a bit and it isn't. Sorry! – Danny May 09 '13 at 22:41
  • @Pascail but what's the main difference between sleep and busy wait, I mean when we use busy wait and not sleep –  Jul 13 '14 at 16:07