How can I write a C program to execute for a certain number of processor seconds? [closed]

StackOverflow https://stackoverflow.com/questions/16471956

  •  21-04-2022
  •  | 
  •  

سؤال

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.

هل كانت مفيدة؟

المحلول

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();
     }
}

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top