Skip to content

Instantly share code, notes, and snippets.

@RicardasSim
Last active November 27, 2019 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RicardasSim/2e9b06be341b4374697e47034fea0c3f to your computer and use it in GitHub Desktop.
Save RicardasSim/2e9b06be341b4374697e47034fea0c3f to your computer and use it in GitHub Desktop.
profiling code, linux, c99
//gcc -std=c99 -Wall -Wextra -Wpedantic -Wshadow main.c
#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //sleep();
#include <time.h>
void printTimeDiff(struct timespec *tm_start, struct timespec *tm_stop)
{
long nanosec_diff = tm_stop->tv_nsec - tm_start->tv_nsec;
if ( nanosec_diff < 0 )
{
printf( "%ld:%09ld\n", tm_stop->tv_sec - tm_start->tv_sec - 1 , 1000000000 + nanosec_diff );
}
else
{
printf( "%ld:%09ld\n", tm_stop->tv_sec - tm_start->tv_sec, nanosec_diff );
}
}
/*
CLOCK_REALTIME - system-wide realtime clock.
CLOCK_PROCESS_CPUTIME_ID - high-resolution per-process timer from the CPU.
CLOCK_THREAD_CPUTIME_ID - thread-specific CPU-time clock.
struct timespec time_start, time_stop;
clock_gettime(CLOCK_REALTIME, &time_start);
...
code
...
clock_gettime(CLOCK_REALTIME, &time_stop);
printTimeDiff(&time_start, &time_stop);
*/
int main()
{
//TEST
struct timespec time_start, time_stop;
printf("wait 1 sec\n");
clock_gettime(CLOCK_REALTIME, &time_start);
sleep(1); //1 sec
clock_gettime(CLOCK_REALTIME, &time_stop);
printTimeDiff(&time_start, &time_stop);
struct timespec nsleep_time;
//1.2 sec
nsleep_time.tv_sec = 1;
nsleep_time.tv_nsec = 200000000;
printf("wait 1.2 sec\n");
clock_gettime(CLOCK_REALTIME, &time_start);
nanosleep(&nsleep_time, NULL);
clock_gettime(CLOCK_REALTIME, &time_stop);
printTimeDiff(&time_start, &time_stop);
nsleep_time.tv_sec = 0;
nsleep_time.tv_nsec = 0;
printf("twenty times +0.07 sec (CLOCK_REALTIME)\n");
for (int i = 0; i < 20; ++i)
{
//just for testing
long tmp = nsleep_time.tv_nsec + 70000000;
if ( tmp >= 1000000000 )
{
nsleep_time.tv_sec += 1;
nsleep_time.tv_nsec = tmp - 1000000000;
}
else
{
nsleep_time.tv_nsec = tmp;
}
clock_gettime(CLOCK_REALTIME, &time_start);
nanosleep(&nsleep_time, NULL);
clock_gettime(CLOCK_REALTIME, &time_stop);
printTimeDiff(&time_start, &time_stop);
}
printf("CLOCK_PROCESS_CPUTIME_ID\n");
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time_start);
nanosleep(&nsleep_time, NULL);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time_stop);
printTimeDiff(&time_start, &time_stop);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment