How to ger RAM and CPU usage of a function? - c

Lets say, I have a function (or functions) which takes a long time (wall time) to execute, for example:
#include "stdafx.h"
#include <math.h>
#include <windows.h>
void fun()
{
long sum = 0L;
for (long long i = 1; i < 10000000; i++){
sum += log((double)i);
}
}
double cputimer()
{
FILETIME createTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;
if ( GetProcessTimes( GetCurrentProcess( ),
&createTime, &exitTime, &kernelTime, &userTime ) != -1 )
{
SYSTEMTIME userSystemTime;
if ( FileTimeToSystemTime( &userTime, &userSystemTime ) != -1 )
return (double)userSystemTime.wHour * 3600.0 +
(double)userSystemTime.wMinute * 60.0 +
(double)userSystemTime.wSecond +
(double)userSystemTime.wMilliseconds / 1000.0;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
double start, stop;
start = cputimer();
fun();
stop = cputimer();
printf("Time taken: %f [seconds]\n", stop - start);
return 0;
}
I would like to measure a CPU load of this function and RAM usage that this function call uses. Is that possible? How can I do this? Im interested in Windows and Linux solutions.

On POSIX you can try using getrusage in the manner similar to how you check the wall time. Not sure about windows.

There is GetProcessTimes function for windows which can give you the CPU time. Also check the Process Status API
Also there is SIGAR which is platform independent.
On Linux you can try with getrusage

Related

Error trying getting clock resolution time

I'm using C and I'm trying to get Clock resolution but I get this value: 0.000000
Here is the code I'm using
#include <time.h>
#include<stdio.h>
double duration(struct timespec start, struct timespec end) {
return end.tv_sec - start.tv_sec
+ ((end.tv_nsec - start.tv_nsec ) / (double) 1000000000.0);
}
double getResolution(){
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
do {
clock_gettime(CLOCK_MONOTONIC, &end);
} while (duration(start, end) == 0.0);
return duration(start, end);
}
int main(){
printf("%f",getResolution());
return 0;
}
You need to increase the precision in your printf("%f");. Using printf("%.12f"); would probably be enough to show some non-zero decimals.
Calculating the floating point duration in the while loop may cause the program to actually perform that calculation if the compiler isn't clever enough to figure out that you only need to see if the clock has changed at all. You could just do a memcmp to compare start and end instead.
Don't take the struct timespecs by value in your duration function. Supply pointers to the function instead. It should be cheaper.
Use the clock_getres function to get the resolution. The runtime value you get with your homebrewed solution depends on what speed the CPU is currently running at etc.
Example:
#include <stdio.h>
#include <string.h>
#include <time.h>
// taking the arguments via pointers:
double duration(const struct timespec* start, const struct timespec* end) {
return end->tv_sec - start->tv_sec +
((end->tv_nsec - start->tv_nsec) / 1000000000.0);
}
double getResolution() {
struct timespec start = {0}, end = {0};
clock_gettime(CLOCK_MONOTONIC, &start);
do {
clock_gettime(CLOCK_MONOTONIC, &end);
// using memcmp below:
} while (memcmp(&start, &end, sizeof start) == 0);
return duration(&start, &end);
}
int main() {
struct timespec base = {0}, res;
// using the proper function to get the resolution:
clock_getres(CLOCK_MONOTONIC, &res);
// comparing the results:
printf("clock_getres = %.12f\n", duration(&base, &res));
printf("getResolution = %.12f\n", getResolution());
}
Demo

How to define C API to get current time count in nanosecond?

I need to define C API ex. GetTimerCountInNS(void) to get current TimerCount in Nanosecond, so using this API call I can calculate total execution time of some work done in nanosecond. Can someone suggest me what is wrong with my GetTimerCountInNS function as when I am calculating total execution time it shows incorrect execution time however for MilliSecond it shows correct one.
I already checked other query related to same one but I could not found exact answer.As I dont want to write all equation into main code when calculating time in nanosecond.
I need to use custom API to get count in Nanosecond and by getting different of start and stop time count I need to get total execution time.
How to get current timestamp in nanoseconds in linux using c
Calculating Function time in nanoseconds in C code
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#define BILLION 1000000000L;
// This API provides incorrect time in NS duration
uint64_t GetTimerCountInNS(void)
{
struct timespec currenttime;
clock_gettime( CLOCK_REALTIME, &currenttime);
//I am not sure here how to calculate count in NS
return currenttime.tv_nsec;
}
// This API provides correct time in MS duration
uint64_t GetTimerCountInMS(void)
{
struct timespec currenttime;
clock_gettime( CLOCK_REALTIME, &currenttime);
return (1000 * currenttime.tv_sec) + ((double)currenttime.tv_nsec / 1e6);
}
int main( int argc, char** argv )
{
struct timespec start, stop;
uint64_t start_ns,end_ns;
uint64_t start_ms,end_ms;
clock_gettime( CLOCK_REALTIME, &start);
start_ms = GetTimerCountInMS();
start_ns = GetTimerCountInNS();
int f = 0;
sleep(3);
clock_gettime( CLOCK_REALTIME, &stop);
end_ms = GetTimerCountInMS();
end_ns = GetTimerCountInNS();
double total_time_sec = ( stop.tv_sec - start.tv_sec ) + (double)( stop.tv_nsec - start.tv_nsec ) / (double)BILLION;
printf( "time in sec \t: %lf\n", total_time_sec );
printf( "time in ms \t: %ld\n", (end_ms - start_ms) );
printf( "time in ns \t: %ld\n", (end_ns - start_ns) );
return EXIT_SUCCESS;
}
Output:
time in sec : 3.000078
time in ms : 3000
time in ns : 76463 // This shows wrong time
A fix:
uint64_t GetTimerCountInNS(void) {
struct timespec currenttime;
clock_gettime(CLOCK_REALTIME, &currenttime);
return UINT64_C(1000000000) * currenttime.tv_sec + currenttime.tv_nsec;
}
In the return, a uint64_t constant is used to promote all other operands of the binary arithmetic operators to uint64_t, in addition to converting seconds to nanoseconds.

C gettimeofday Doesn't Work Properly With GoLang

I've a simple C function which I call from GoLang. In my C function I'm using gettimeofday function. I understand that this function doesn't give accurate time and I'm okay with that as I only need to get some idea. I just want to get the time difference to run a big for loop.When I run the C function from a C program, it works fine. The for loop takes around 3 seconds to finish. But if I call the same function from GoLang, it looks like that it doesn't take any time in the for loop The program finishes immediately.
Here goes my code.
timetest.h
#include <sys/time.h>
#include<stdio.h>
int TimeTest(){
int i=0;
int j = 1000000000;
unsigned long long startMilli=0;
unsigned long long endMilli=0;
struct timeval te;
gettimeofday(&te, NULL);
startMilli = te.tv_sec*1000LL + te.tv_usec/1000;
for (i=0; i<1000000000; i++){
if (j-1 == i){
printf("matched\n");
}
}
gettimeofday(&te, NULL);
endMilli = te.tv_sec*1000LL + te.tv_usec/1000;
printf("Start = %d End = %d Total time %d\n", startMilli, endMilli, endMilli - startMilli);
return endMilli - startMilli;
}
test.go
package main
// #include <sys/time.h>
// #include "timetest.h"
import "C"
import (
"fmt"
)
func main(){
diff := C.TimeTest()
fmt.Println(diff)
}
Main.c
#include"timetest.h"
int main(){
int diff = TimeTest();
printf("%d\n", diff);
return 0;
}

using gettimeofday() equivalents on windows

I'm trying to use 2 different equivalents for UNIX's gettimeofday() function on Windows, using Visual Studio 2013.
I took the first one from here. As the second one, I'm using the _ftime64_s function, as explained here.
They work, but not as I expected. I want to get different values when printing the seconds, or at least the milliseconds, but I get the same value for the printings with gettimeofday() (mytime1 & mytime2) and with _ftime64_s (mytime3 & mytime4).
However, it worth mentioning that the value of the milliseconds is indeed different between these two functions (that is, the milliseconds value of mytime1/mytime2 is different from mytime3/mytime4).
Here's my code:
#include <stdio.h>
#include <Windows.h>
#include <stdint.h>
#include <sys/timeb.h>
#include <time.h>
#define WIN32_LEAN_AND_MEAN
int gettimeofday(struct timeval * tp, struct timezone * tzp)
{
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t)file_time.dwLowDateTime);
time += ((uint64_t)file_time.dwHighDateTime) << 32;
tp->tv_sec = (long)((time - EPOCH) / 10000000L);
tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
return 0;
}
int main()
{
/* working with struct timeval and gettimeofday equivalent */
struct timeval mytime1;
struct timeval mytime2;
gettimeofday(&(mytime1), NULL);
gettimeofday(&(mytime2), NULL);
printf("Seconds: %d\n", (int)(mytime1.tv_sec));
printf("Milliseconds: %d\n", (int)(mytime1.tv_usec));
printf("Seconds: %d\n", (int)(mytime2.tv_sec));
printf("Milliseconds: %d\n", (int)(mytime2.tv_usec));
/* working with _ftime64_s */
struct _timeb mytime3;
struct _timeb mytime4;
_ftime64_s(&mytime3);
_ftime64_s(&mytime4);
printf("Seconds: %d\n", mytime3.time);
printf("Milliseconds: %d\n", mytime3.millitm);
printf("Seconds: %d\n", mytime4.time);
printf("Milliseconds: %d\n", mytime4.millitm);
return (0);
}
I tried other format specifiers (%f, %lu) and castings ((float), (double), (long), (size_t)), but it didn't matter. Suggestions will be welcomed.
QueryPerformanceCounter is used for accurate timing on windows. Usage can be as follows:
uint64_t microseconds()
{
LARGE_INTEGER fq, t;
QueryPerformanceFrequency(&fq);
QueryPerformanceCounter(&t);
return (1000000 * t.QuadPart) / fq.QuadPart;
}
This does not work with any EPOCH as far as I know. For that you need GetSystemTimePreciseAsFileTime which is only available on Windows 8 and higher.
uint64_t MyGetSystemTimePreciseAsFileTime()
{
HMODULE lib = LoadLibraryW(L"kernel32.dll");
if (!lib) return 0;
FARPROC fp = GetProcAddress(lib, "GetSystemTimePreciseAsFileTime");
ULARGE_INTEGER largeInt;
largeInt.QuadPart = 0;
if (fp)
{
T_GetSystemTimePreciseAsFileTime* pfn = (T_GetSystemTimePreciseAsFileTime*)fp;
FILETIME fileTime = { 0 };
pfn(&fileTime);
largeInt.HighPart = fileTime.dwHighDateTime;
largeInt.LowPart = fileTime.dwLowDateTime;
}
FreeLibrary(lib);
return largeInt.QuadPart;
}
int main()
{
uint64_t t1 = microseconds();
uint64_t t2 = microseconds();
printf("t1: %llu\n", t1);
printf("t2: %llu\n", t2);
return (0);
}

millisecond precision timing of functions in C - crossplatform

Is there a way to get milliseconds precision, accurate (at least within a few ms) times in C using a cross-platform approach?
on a POSIX system I can use sys/time.h, but that is not cross-platform.
the stdlib time() function only gives second level precision
I haven't found a cross-platform solution to measuring time in C, per se. However, what I do is use almost identical functions for Unix and Windows. I created this gist because I always have to re-look this up every time. In short:
Unix
#include <time.h>
long diff_micro(struct timespec *start, struct timespec *end)
{
/* us */
return ((end->tv_sec * (1000000)) + (end->tv_nsec / 1000)) -
((start->tv_sec * 1000000) + (start->tv_nsec / 1000));
}
long diff_milli(struct timespec *start, struct timespec *end)
{
/* ms */
return ((end->tv_sec * 1000) + (end->tv_nsec / 1000000)) -
((start->tv_sec * 1000) + (start->tv_nsec / 1000000));
}
int main(int argc, char **argv)
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
// Activity to be timed
sleep(1000);
clock_gettime(CLOCK_MONOTONIC, &end);
printf("%ld us\n", diff_micro(&start, &end));
printf("%ld ms\n", diff_milli(&start, &end));
return 0;
}
source for Unix solution
Win32
#include <Windows.h>
long diff_micro(LARGE_INTEGER *start, LARGE_INTEGER *end)
{
LARGE_INTEGER Frequency, elapsed;
QueryPerformanceFrequency(&Frequency);
elapsed.QuadPart = end->QuadPart - start->QuadPart;
elapsed.QuadPart *= 1000000;
elapsed.QuadPart /= Frequency.QuadPart;
return elapsed.QuadPart;
}
long diff_milli(LARGE_INTEGER *start, LARGE_INTEGER *end)
{
LARGE_INTEGER Frequency, elapsed;
QueryPerformanceFrequency(&Frequency);
elapsed.QuadPart = end->QuadPart - start->QuadPart;
elapsed.QuadPart *= 1000;
elapsed.QuadPart /= Frequency.QuadPart;
return elapsed.QuadPart;
}
int main(int argc, char **argv)
{
LARGE_INTEGER StartingTime, EndingTime;
QueryPerformanceCounter(&StartingTime);
// Activity to be timed
Sleep(1000);
QueryPerformanceCounter(&EndingTime);
printf("%ld us\n", diff_micro(&StartingTime, &EndingTime));
printf("%ld ms\n", diff_milli(&StartingTime, &EndingTime));
return 0;
}
source used for Win32 solution
You can try something like this:-
#include <time.h>
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);
See this Link
The best way is using std::chrono
#include <chrono>
...
auto begin = std::chrono::high_resolution_clock::now();
...
auto end = std::chrono::high_resolution_clock::now();
elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();

Resources