User Tools

Site Tools


programming:posix

POSIX

Execution Time & Timestamps (gettimeofday)

#include <sys/time.h>
 
struct timeval t;
uint64_t start;
 
if (gettimeofday(&t, NULL) == 0)
{
    start = 1000000ULL * t.tv_sec + t.tv_usec;
} // if
 
:
:
 
if (gettimeofday(&t, NULL) == 0)
{
    printf("%llu us", (1000000ULL * t.tv_sec + t.tv_usec) - start);
} // if

The resolution of function gettimeofday() depends on the platform, but mostly all Linux like systems implement it using high resolution timers.

Name of Current Process (getpid)

The following code fragment determines the executable name (possibly incl. path) of current process in variable exe.

#include <unistd.h>
#include <stdio.h>
 
char exe[256]; /* to be adopted, possibly by dynamic alloc */
char path[32]; /* path of 'exe' link in proc filesystem */
ssize_t len;
 
snprintf(path, sizeof(path), "/proc/%d/exe", (int) getpid()); /* not portable */
buf[sizeof(path) - 1] = '\0';
len = readlink(path, exe, sizeof(exe));
 
if (len != -1)
    exe[len] = '\0';
else
    ; /* implement error handling */

The implementation works under Linux and some other *nix derivates, but not for all systems (you might use #ifdef __linux__ if this method appropriate).

programming/posix.txt · Last modified: 2016/12/13 11:25 by Ralf Hoppe