Timer in C Linux - timer

I was trying to create a timer using gettimeofday. A function "time" has been called for resetting and getting the current time for the timer. But the program is giving garbage values when i tried to get second tine value. Please help
#include<stdio.h>
#include <sys/time.h>
#include <stdlib.h>
struct timeval cur;
double time(int a);
main() {
time(0);
printf("%lf\n",time(1));
sleep(3);
printf("%lf\n",time(1));
}
double time(int a) {
double rtime;
if(a==0) {
gettimeofday(&cur,NULL);
rtime=(double)(cur.tv_sec);
printf("%lf\n",rtime);
} else if(a==1) {
gettimeofday(&cur,NULL);
return((double)(cur.tv_sec-rtime));
}
}

Your routine time() will not remember rtimeunless you
specify rtime as static:
static double rtime;
And: It's unclear why you specify those numbers as doubles.

Related

Why it isn't working? I have seen examples using this, but when I use it, it crashes. Why?(C)

Why can't I do g->n=n ? Can someone explain?
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX 100000
int N[]={100,200,300,400,500,600,700,800,900,1000};
double B[]={0.125, 0.250, 0.375, 0.5, 0.625, 0.750, 0.875};
typedef struct Graph
{
int n;
int M[MAX][MAX];
int val;
int adjacent[MAX-1];
}G;
struct Graph * RandomDirectedGraph(int n, double b)
{
struct Graph * g = (struct Graph*)malloc(sizeof(struct Graph));
g->n=n;
int u,i,v;
for(u=0;u<n;u++)
{
for(i=0;i<n;i++)
{
g->M[u][i]=0;
}
}
int m=b*n*n;
for(i=0;i<m;i++)
{
do
{
u=rand()%n;
v=rand()%n;
}
while(u==v || g->M[u][v]==1);
g->M[u][v]=1;
}
};
int main()
{
int i,j,n,b;
for(i=0;i<sizeof(N)/sizeof(*N);i++)
{
for(j=0;j<sizeof(B)/sizeof(*B);j++)
{
RandomDirectedGraph(N[i],B[j]);
}
}
return 0;
}
When I compile and run it, ERROR pops up and says that some memory can't be written. I don't know what I'm doing wrong here.
The issue is that everytime you are executing the method RandomDirectedGraph, your application tries to reserve about 40GB of RAM memory. I guess your computer doesn't have that much.
Furthermore you should release all memory by calling free on the pointers.
For such big matrices, you don't use classic C matrices. You need external librarys for sparse matrix calculations like https://www.alglib.net/matrixops/sparse.php

print result using system calls

For my OS class, I need to print out the result of this matrix multiplication using only system calls. Following my lecture notes, I wrote up this piece of code. I use :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 1000
// Matrix
long long int A[N][N],B[N][N],R[N][N];
int main(int argc, char *argv[])
{
int x,y,z;
char str[100];
/* Matrix inicialization */
for(y=0;y<N;y++)
for(x=0;x<N;x++)
{
A[y][x]=x;
B[y][x]=y;
R[y][x]=0;
}
/* Matrix multiplication */
for(y=0;y<N;y++)
for(z=0;z<N;z++)
for(x=0;x<N;x++)
{
R[y][x]+= A[y][z] * B[z][x];
}
//System calls for printing the result
sprintf(str,"%lld\n",R);
write(1,str,strlen(str));
exit(0);
}
Now, it's printing a just a 14295680 in the console. The professor gave us a file with machine code and it's printing 332833500, which seems more reasoneable.
Thanks in advance.
Edit: changed type on the printf call
Edit2: fix R[N][N]
Just replace the sprintf value:
sprintf(str,"%lld\n",R[N-1][N-1]); // = 332833500
write(1,str,strlen(str));
instead of
sprintf(str,"%lld\n",R); // this is a pointer
write(1,str,strlen(str));

Invalid conversion from int* to int using functions

I have this "simple" problem: I have in input 2 int numbers and i must output them in decreasing order.
#include <stdio.h>
#include <iostream>
int fnum()
{
int NUM;
scanf("%d",&NUM);
return NUM;
}
void frisultato(int x,int y)
{
if (x>y)
{
printf("%d",x);
printf("%d",y);
}
else
{
printf("%d",y);
printf("%d",x);
}
return;
}
int main()
{
int A,B;
A=fnum;
B=fnum;
frisultato(A,B);
}
I recieve an error at
A=fnum;
B=fnum;
my compiler says: invalid conversion from int(*)() to int.
This is the first time i use functions, what is the problem? Thank you!
Michelangelo.
A=fnum;
B=fnum;
You're not actually calling the function fnum here. You're attempting to assign a pointer to the function to the int variables A and B.
To call the function, do this:
A=fnum();
B=fnum();
Sorry, but since you seem to be new at programming, I couldn't help but refactor/comment on your code:
#include <stdio.h>
#include <iostream>
int fnum()
{
int num;
scanf("%d",&num);
return num;
}
void frisultato(int x, int y)
{
if (x>y)
{
printf("%d",x);
printf("%d",y);
}
else
{
printf("%d",y);
printf("%d",x);
}
/* No need to return in void */
}
int main()
{
/*
Variables in C are all lowercase.
UPPER_CASE is usually used for macros and preprocessor directives
such as
#define PI 3.14
*/
int a, b;
a = fnum(); //Function calls always need parenthesis, even if they are empty
b = fnum();
frisultato(a, b);
/*
Your main function should return an integer letting whoever
ran it know if it was successful or not.
0 means everything went well, anything else means something went wrong.
*/
return 0;
}
Also, don't sign your name on StackOverflow questions.

"Generic" function in C - use same time-measuring function for 2 different libraries

I found here, on SO, a simple function to measure the execution time of a function in C:
#include <stdio.h>
#include <stdint.h>
#include <time.h>
int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)
{
return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);
}
int main(int argc, char **argv)
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
// Some code I am interested in measuring
clock_gettime(CLOCK_MONOTONIC, &end);
uint64_t timeElapsed = timespecDiff(&end, &start);
}
Now I would like to use it to measure some cryptographic function executions. For now on, Im interesting only in Openssl and Crypto++ (but would like to extend the list with other libraries).
In C++ I would use templates for this, but how about C? Let's say, I have 2 functions:
void md4_openssl(...); and void md4_cryptopp(...); where all the parameters setups (keys, buffers, ...) are INSIDE those functions. Now, how can I make my measruring function more "generic"? In the way that something like this would be possible:
void measureTime()
{
function(); // could be md4_openssl or md4_cryptopp
}
Of course, I would use opnessl if installed, but if it is not, it will call cryptopp function
The obvious way is a pass a pointer to function to measureTime():
uint64_t measureTime(void (*fp)(void)) {
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
fp(); // Call the function you want to measure
clock_gettime(CLOCK_MONOTONIC, &end);
return timespecDiff(&end, &start);
}
void measure_ssl(void) {
md4_openssl(1, 2, 3, whatever); // Setup and call however you need to
}
void measure_crypt(void) {
md4_cryptopp(1, 2, 3, whatever); // Setup and call however you need to
}
int main(void) {
uint64_t t1 = measureTime(measure_ssl);
uint64_t t2 = measureTime(measure_crypt);
// Do something with t1 and t2
return 0;
}
EDIT: In response to your comment, any function pointer you pass to a function must have the signature matching the parameter. If you need to call functions which have different signatures, then you need to wrap them as the above code does.
If your wrapper function can take care of the parameters, then you can just use the above code without modification. In other words, measure_ssl() can call md4_openssl(1, 2, 3, "more", "args") and measure_crypt() can call md4_cryptopp(5.4, "different", ARGS) or whatever.
If you do need to actually provide the arguments to measureTime(), you'll have to pass information to your wrapper functions and have them do some interpretation. If each function took, say, one pointer, but of a different type, you could just pass a single void * and pass it on.
If the arguments can be completely different and unpredictable, then the simplest way to do it is create a struct and pass the address of that, for instance:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
void func1(int a, int b, int c) {
printf("Let's count to %d, %d and %d!\n", a, b, c);
}
struct func1_params {
int a;
int b;
int c;
};
void func2(double d, const char * c) {
printf("There are %f %ss\n", d, c);
}
struct func2_params {
double d;
const char * c;
};
void func1_wrap(void * params) {
struct func1_params * p = params;
func1(p->a, p->b, p->c);
}
void func2_wrap(void * params) {
struct func2_params * p = params;
func2(p->d, p->c);
}
int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) {
return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);
}
uint64_t measureTime(void (*fp)(void *), void * params) {
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
fp(params);
clock_gettime(CLOCK_MONOTONIC, &end);
return timespecDiff(&end, &start);
}
int main(void) {
struct func1_params p1 = {1, 2, 3};
uint64_t t1 = measureTime(func1_wrap, &p1);
struct func2_params p2 = {3.14159, "pie"};
uint64_t t2 = measureTime(func2_wrap, &p2);
printf("First func took time %" PRIu64 " units.\n", t1);
printf("Second func took time %" PRIu64 " units.\n", t2);
return 0;
}
This is generic, in that measureTime() doesn't need to know anything about the functions you're calling, or anything about the struct. You could compile that into a library, and then much later write, say, func1_wrap() and struct func1_params and pass them in. You can measure the time of any function you like just by writing a struct to contain the arguments and a wrapper function of type void (*)(void *) to accept a pointer to that struct and pass the members as arguments to the function you're interested in.
In the above code, I've provided the definitions of func1() and func2() to provide a complete working example, but you can think of these as your md4_openssl() and md4_cryptopp() functions instead, and have your wrapper functions call those.

GCC division truncates (rounding problem)

Using GCC on the Ubuntu Linux 10.04, I have unwanted rounding after a division.
I tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void FormatReading(int temp)
{
double reading = temp / 100;
printf("%f\n",reading); /* displays 226.000000, was expecting 226.60 */
}
int main(void)
{
FormatReading(22660);
return 0;
}
It was suggested to me to try:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void FormatReading(int temp)
{
long reading = temp ;
reading = reading / 100;
printf("%3.2ld\n",reading); /* displays 226 */
}
int main(void)
{
FormatReading(22660);
return 0;
}
I also tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void FormatReading(int temp)
{
long reading = temp ;
double reading2 = reading / 100;
printf("%3.2f\n",reading2); /* displays 226.00 */
}
int main(void)
{
FormatReading(22660);
return 0;
}
I also tried the round function using include math.h with compiler tag -lm in various ways, but did not find what I was looking for.
Any help greatly appreciated.
Best regards,
Bert
double reading = temp / 100.0;
^^
temp / 100 is an integer division - that you assign the result to a double doesn't change this.
You are using integer division which always gives integral results rather than fractions, and then the result is being assigned to a double. Divide by 100.0 instead of 100 to get the behavior you want.

Resources