CPU usage in C (as percentage) - c

How can I get CPU usage as percentage using C?
I have a function like this:
static int cpu_usage (lua_State *L) {
clock_t clock_now = clock();
double cpu_percentage = ((double) (clock_now - program_start)) / get_cpus() / CLOCKS_PER_SEC;
lua_pushnumber(L,cpu_percentage);
return 1;
}
"program_start" is a clock_t that I use when the program starts.
Another try:
static int cpu_usage(lua_State *L) {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
lua_pushnumber(L,ru.ru_utime.tv_sec);
return 1;
}
Is there any way to measure CPU? If I call this function from time to time it keeps returning me the increasing time... but that´s not what I want.
PS: I'm using Ubuntu.
Thank you! =)

Your function should work as expected. From clock
The clock() function shall return the implementation's best approximation to the processor time used by the process since the beginning of an implementation-defined era related only to the process invocation.
This means, it returns the CPU time for this process.
If you want to calculate the CPU time relative to the wall clock time, you must do the same with gettimeofday. Save the time at program start
struct timeval wall_start;
gettimeofday(&wall_start, NULL);
and when you want to calculate the percentage
struct timeval wall_now;
gettimeofday(&wall_now, NULL);
Now you can calculate the difference of wall clock time and you get
double start = wall_start.tv_sec + wall_start.tv_usec / 1000000;
double stop = wall_now.tv_sec + wall_now.tv_usec / 1000000;
double wall_time = stop - start;
double cpu_time = ...;
double percentage = cpu_time / wall_time;

Related

Printing execution time, two decimal points

I'm using the following function to estimate the execution time (performance) of a function:
double print_time(struct timeval *start, struct timeval *end)
{
double usec;
usec = (end->tv_sec * 1000000 + end->tv_usec) - (start->tv_sec * 1000000 + start->tv_usec);
return usec / 1000.0;
}
Simple Code:
struct timeval start, end;
double t = 0.0;
gettimeofday(&start, NULL);
... //code
gettimeofday(&end, NULL);
t = print_time(&start, &end);
printf("%.2f", t);
Why when I print the variable I see the time formatted in this manner: 3.613.97? The problem is related for the two points. What means the first point and the second point? Normally I always saw just one decimal point to separate the digits.
Include the right headers:
#include <time.h>
#include <stdio.h>
At the beginning of the program:
clock_t starttime = clock();
At the end of the program:
printf("elapsed time: %.3f s\n", (float)(clock() - starttime) / CLOCKS_PER_SEC);
This works on several platforms (including Windows with MinGW-w64), but the resolution of the timer (CLOCKS_PER_SEC) may vary per platform.
Note that this measures the clock cycles used by your application, instead of the time passed between start and end.
So while it is not an exact chronometer, it gives a better idea of how much time your program actually took to run.

Measuring processor ticks in C

I wanted to calculate the difference in execution time when executing the same code inside a function. To my surprise, however, sometimes the clock difference is 0 when I use clock()/clock_t for the start and stop timer. Does this mean that clock()/clock_t does not actually return the number of clicks the processor spent on the task?
After a bit of searching, it seemed to me that clock_gettime() would return more fine grained results. And indeed it does, but I instead end up with an abitrary number of nano(?)seconds. It gives a hint of the difference in execution time, but it's hardly accurate as to exactly how many clicks difference it amounts to. What would I have to do to find this out?
#include <math.h>
#include <stdio.h>
#include <time.h>
#define M_PI_DOUBLE (M_PI * 2)
void rotatetest(const float *x, const float *c, float *result) {
float rotationfraction = *x / *c;
*result = M_PI_DOUBLE * rotationfraction;
}
int main() {
int i;
long test_total = 0;
int test_count = 1000000;
struct timespec test_time_begin;
struct timespec test_time_end;
float r = 50.f;
float c = 2 * M_PI * r;
float x = 3.f;
float result_inline = 0.f;
float result_function = 0.f;
for (i = 0; i < test_count; i++) {
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &test_time_begin);
float rotationfraction = x / c;
result_inline = M_PI_DOUBLE * rotationfraction;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &test_time_end);
test_total += test_time_end.tv_nsec - test_time_begin.tv_nsec;
}
printf("Inline clocks %li, avg %f (result is %f)\n", test_total, test_total / (float)test_count,result_inline);
for (i = 0; i < test_count; i++) {
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &test_time_begin);
rotatetest(&x, &c, &result_function);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &test_time_end);
test_total += test_time_end.tv_nsec - test_time_begin.tv_nsec;
}
printf("Function clocks %li, avg %f (result is %f)\n", test_total, test_total / (float)test_count, result_inline);
return 0;
}
I am using gcc version 4.8.4 on Linux 3.13.0-37-generic (Linux Mint 16)
First of all: As already mentioned in the comments, clocking a single run of execution one by the other will probably do you no good. If all goes down the hill, the call for getting the time might actually take longer than the actual execution of the operation.
Please clock multiple runs of the operation (including a warm up phase so everything is swapped in) and calculate the average running times.
clock() isn't guaranteed to be monotonic. It also isn't the number of processor clicks (whatever you define this to be) the program has run. The best way to describe the result from clock() is probably "a best effort estimation of the time any one of the CPUs has spent on calculation for the current process". For benchmarking purposes clock() is thus mostly useless.
As per specification:
The clock() function returns the implementation's best approximation to the processor time used by the process since the beginning of an implementation-dependent time related only to the process invocation.
And additionally
To determine the time in seconds, the value returned by clock() should be divided by the value of the macro CLOCKS_PER_SEC.
So, if you call clock() more often than the resolution, you are out of luck.
For profiling/benchmarking, you should --if possible-- use one of the performance clocks that are available on modern hardware. The prime candidates are probably
The HPET
The TSC
Edit: The question now references CLOCK_PROCESS_CPUTIME_ID, which is Linux' way of exposing the TSC.
If any (or both) are available depends on the hardware in is also operating system specific.
After googling a little bit I can see that clock() function can be used as a standard mechanism to find the tome taken for execution , but be aware that the time will be varying at different time depending upon the load of your processor,
You can just use the below code for calculation
clock_t begin, end;
double time_spent;
begin = clock();
/* here, do your time-consuming job */
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

How to measure execution time of several functions in a loop in C

I hope to find a way to measure execution time of several functions in a for loop in C. For example, there is code like:
for(;;)
{
func1();
func2();
func3();
}
I want to know how much time program spends totally on func1() (or func2, func3).
I know I can use clock() to measure time. However, in this case if I write the code like:
for(;;)
{
a = clock();
func1();
b = clock();
time_func1 += (b-a);
a = clock();
func2();
b = clock();
time_func2 += (b-a);
a = clock();
func3();
b = clock();
time_func3 += (b-a);
}
It looks like too stupid and the result is not accurate.
If you are on Linux, I'd suggest you to use clock_gettime. This enables precise time measurement with several clocks, also with high resolution. clock itself has a low resolution.
Maybe a word regarding its use:
timespec t1, t2;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t1);
/* CODE TO BE MEASURED */
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t2);
clock() has a very low resolution. Depending your OS, there are more accurate functions.
In Windows there's QueryPerformanceCounters.
clock() will also give not the real execution time if multi-threaded code is present.
Sebastian is right,
According to the man page, the POSIX function clock() returns an approximation of the clock ticks (what do they mean by approximation ?) used by the program. You have to divide by the number of clocks per second to get the execution time.
This is done by:
int main() {
clock_t start;
clock_t end;
double cpu_time_used;
start = clock();
# do some computations
end = clock();
cpu_time_used = ((double) (end-start)) / CLOCKS_PER_SEC;
}
It is easy to use and you get the CPU ticks for the calling process, but the precision is in milliseconds.
If you need more precision, the POSIX function clock_gettime() precision is order of nanoseconds. You can specify to retrieve the system-wide, per-process or thread-specific elapsed time. Here's an example:
int main() {
timespec start;
timespec end;
double cpu_time_used;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
# do some computations
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);
cpu_time_used = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000000.0;
}
If you want measure the time and further want to optimize those function better to go with profiling tools like oprofile there you will get to know which function is taking how much time.with 'opannotate' you will get to know in better way

Measuring elapsed time in linux for a c program

I am trying to measure elapsed time in Linux. My answer keeps returning zero which makes no sense to me. Below is the way i measure time in my program.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
main()
{
double p16 = 1, pi = 0, precision = 1000;
int k;
unsigned long micros = 0;
float millis = 0.0;
clock_t start, end;
start = clock();
// This section calculates pi
for(k = 0; k <= precision; k++)
{
pi += 1.0 / p16 * (4.0 / (8 * k + 1) - 2.0 / (8 * k + 4) - 1.0 / (8 * k + 5) - 1.0 / (8 * k + 6));
p16 *= 16;
}
end = clock();
micros = end - start;
millis = micros / 1000;
printf("%f\n", millis); //my time keeps being returned as 0
printf("this value of pi is : %f\n", pi);
}
Three alternatives
clock()
gettimeofday()
clock_gettime()
clock_gettime() goes upto nanosecond accuracy and it supports 4 clocks.
CLOCK_REALTIME
System-wide realtime clock. Setting this clock requires appropriate privileges.
CLOCK_MONOTONIC
Clock that cannot be set and represents monotonic time since some unspecified starting point.
CLOCK_PROCESS_CPUTIME_ID
High-resolution per-process timer from the CPU.
CLOCK_THREAD_CPUTIME_ID
Thread-specific CPU-time clock.
You can use it as
#include <time.h>
struct timespec start, stop;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
/// do something
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);
double result = (stop.tv_sec - start.tv_sec) * 1e6 + (stop.tv_nsec - start.tv_nsec) / 1e3; // in microseconds
Note: The clock() function returns CPU time for your process, not wall clock time. I believe this is what the OP was interested in. If wall clock time is desired, then gettimeofday() is a good choice as suggested by an earlier answer. clock_gettime() can do either one if your system supports it; on my linux embedded system clock_gettime() is not supported, but clock() and gettimeofday() are.
Below is the code for getting wall clock time using gettimeofday()
#include <stdio.h> // for printf()
#include <sys/time.h> // for clock_gettime()
#include <unistd.h> // for usleep()
int main() {
struct timeval start, end;
long secs_used,micros_used;
gettimeofday(&start, NULL);
usleep(1250000); // Do the stuff you want to time here
gettimeofday(&end, NULL);
printf("start: %d secs, %d usecs\n",start.tv_sec,start.tv_usec);
printf("end: %d secs, %d usecs\n",end.tv_sec,end.tv_usec);
secs_used=(end.tv_sec - start.tv_sec); //avoid overflow by subtracting first
micros_used= ((secs_used*1000000) + end.tv_usec) - (start.tv_usec);
printf("micros_used: %d\n",micros_used);
return 0;
}
To start with you need to use floating point arithmetics. Any integer value divided by a larger integer value will be zero, always.
And of course you should actually do something between getting the start and end times.
By the way, if you have access to gettimeofday it's normally preferred over clock as it has higher resolution. Or maybe clock_gettime which has even higher resolution.
There are two issues with your code as written.
According to man 3 clock, the resolution of clock() is in CLOCKS_PER_SEC increments per second. On a recent-ish Cygwin system, it's 200. Based on the names of your variables, you are expecting the value to be 1,000,000.
This line:
millis = micros / 1000;
will compute the quotient as an integer, because both operands are integers. The promotion to a floating-point type occurs at the time of the assignment to millis, at which point the fractional part has already been discarded.
To compute the number of seconds elapsed using clock(), you need to do something like this:
clock_t start, end;
float seconds;
start = clock();
// Your code here:
end = clock();
seconds = end - start; // time difference is now a float
seconds /= CLOCKS_PER_SEC; // this division is now floating point
However, you will almost certainly not get millisecond accuracy. For that, you would need to use gettimeofday() or clock_gettime(). Further, you probably want to use double instead of float, because you are likely going to wind up subtracting very large numbers with a very tiny difference. The example using clock_gettime() would be:
#include <time.h>
/* Floating point nanoseconds per second */
#define NANO_PER_SEC 1000000000.0
int main(void)
{
struct timespec start, end;
double start_sec, end_sec, elapsed_sec;
clock_gettime(CLOCK_REALTIME, &start);
// Your code here
clock_gettime(CLOCK_REALTIME, &end);
start_sec = start.tv_sec + start.tv_nsec / NANO_PER_SEC;
end_sec = end.tv_sec + end.tv_nsec / NANO_PER_SEC;
elapsed_sec = end_sec - start_sec;
printf("The operation took %.3f seconds\n", elapsed_sec);
return 0;
}
Since NANO_PER_SEC is a floating-point value, the division operations are carried out in floating-point.
Sources:
man pages for clock(3), gettimeofday(3), and clock_gettime(3).
The C Programming Language, Kernighan and Ritchie
Try Sunil D S's answer but change micros from unsigned long to type float or double, like this:
double micros;
float seconds;
clock_t start, end;
start = clock();
/* Do something here */
end = clock();
micros = end - start;
seconds = micros / 1000000;
Alternatively, you could use rusage, like this:
struct rusage before;
struct rusage after;
float a_cputime, b_cputime, e_cputime;
float a_systime, b_systime, e_systime;
getrusage(RUSAGE_SELF, &before);
/* Do something here! or put in loop and do many times */
getrusage(RUSAGE_SELF, &after);
a_cputime = after.ru_utime.tv_sec + after.ru_utime.tv_usec / 1000000.0;
b_cputime = before.ru_utime.tv_sec + before.ru_utime.tv_usec / 1000000.0;
e_cputime = a_cputime - b_cputime;
a_systime = after.ru_stime.tv_sec + after.ru_stime.tv_usec / 1000000.0;
b_systime = before.ru_stime.tv_sec + before.ru_stime.tv_usec / 1000000.0;
e_systime = a_systime - b_systime;
printf("CPU time (secs): user=%.4f; system=%.4f; real=%.4f\n",e_cputime, e_systime, seconds);
Units and precision depend on how much time you want to measure but either of these should
provide reasonable accuracy for ms.
When you divide, you might end up with a decimal, hence you need a flaoting point number to store the number of milli seconds.
If you don't use a floating point, the decimal part is truncated. In your piece of code, the start and end are ALMOST the same. Hence the result after division when stored in a long is "0".
unsigned long micros = 0;
float millis = 0.0;
clock_t start, end;
start = clock();
//code goes here
end = clock();
micros = end - start;
millis = micros / 1000;

OS independent C library for calculating time lapse?

So in my game I need to simulate the physics in a hardware independent manner.
I'm going to use a fixed time-step simulation, but I need to be able to calculate how much time is passing between calls.
I tried this and got nowhere:
#include <time.h>
double time_elapsed;
clock_t last_clocks = clock();
while (true) {
time_elapsed = ( (double) (clock() - last_clocks) / CLOCKS_PER_SEC);
last_clocks = clock();
printf("%f\n", time_elapsed);
}
Thanks!
You can use gettimeofday to get the number of seconds plus the number of microseconds since the Epoch. If you want the number of seconds, you can do something like this:
#include <sys/time.h>
float getTime()
{
struct timeval time;
gettimeofday(&time, 0);
return (float)time.tv_sec + 0.000001 * (float)time.tv_usec;
}
I misunderstood your question at first, but you might find the following method of making a fixed-timestep physics loop useful.
There are two things you need to do to make a fixed-timestep physics loop.
First, you need to calculate the time between now and the last time you ran physics.
last = getTime();
while (running)
{
now = getTime();
// Do other game stuff
simulatePhysics(now - last);
last = now;
}
Then, inside of the physics simulation, you need to calculate a fixed timestep.
void simulatePhysics(float dt)
{
static float timeStepRemainder; // fractional timestep from last loop
dt += timeStepRemainder * SIZE_OF_TIMESTEP;
float desiredTimeSteps = dt / SIZE_OF_TIMESTEP;
int nSteps = floorf(desiredTimeSteps); // need integer # of timesteps
timeStepRemainder = desiredTimeSteps - nSteps;
for (int i = 0; i < nSteps; i++)
doPhysics(SIZE_OF_TIMESTEP);
}
Using this method, you can give whatever is doing physics (doPhysics in my example) a fixed timestep, while keeping a synchronization between real time and game time by calculating the right number of timesteps to simulate since the last time physics was run.
clock_gettime(3).

Resources