C gettimeofday Doesn't Work Properly With GoLang - c

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;
}

Related

How to print to terminal one char and then pause and print another?

I've been trying to print to the terminal with a pause, it's better explained with the following code:
I'm trying to have X print to the terminal and then wait 5s and have X print again but when I run the code, it waits 5s and prints XX can anyone help me get the proper functionality?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static void sleepMs(long long delayMs){
const long long NS_PER_MS = 1000 * 1000;
const long long NS_PER_SECOND = 1000000000;
long long delayNs = delayMs * NS_PER_MS;
int seconds = delayNs / NS_PER_SECOND;
int nanoSeconds = delayNs % NS_PER_SECOND;
struct timespec reqDelay = {seconds, nanoSeconds};
nanosleep(&reqDelay, (struct timespec *) NULL);
}
int main()
{
printf("X");
sleepMs(5000);
printf("X");
return 0;
}
Thank you in advance, sorry for any missing tags.
EDIT: I want them to print on the same line
You need to flush the output stream if you want to see the result before printing a \n:
putchar('X');
fflush(stdout);

How to make thread safe program?

On a 64-bit architecture pc, the next program should return the result 1.350948.
But it is not thread safe and every time I run it gives (obviously) a different result.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <pthread.h>
const unsigned int ndiv = 1000;
double res = 0;
struct xval{
double x;
};
// Integrate exp(x^2 + y^2) over the unit circle on the
// first quadrant.
void* sum_function(void*);
void* sum_function(void* args){
unsigned int j;
double y = 0;
double localres = 0;
double x = ((struct xval*)args)->x;
for(j = 0; (x*x)+(y*y) < 1; y = (++j)*(1/(double)ndiv)){
localres += exp((x*x)+(y*y));
}
// Globla variable:
res += (localres/(double)(ndiv*ndiv));
// This is not thread safe!
// mutex? futex? lock? semaphore? other?
}
int main(void){
unsigned int i;
double x = 0;
pthread_t thr[ndiv];
struct xval* xvarray;
if((xvarray = calloc(ndiv, sizeof(struct xval))) == NULL){
exit(EXIT_FAILURE);
}
for(i = 0; x < 1; x = (++i)*(1/(double)ndiv)){
xvarray[i].x = x;
pthread_create(&thr[i], NULL, &sum_function, &xvarray[i]);
// Should check return value.
}
for(i = 0; i < ndiv; i++){
pthread_join(thr[i], NULL);
// If
// pthread_join(thr[i], &retval);
// res += *((double*)retval) <-?
// there would be no problem.
}
printf("The integral of exp(x^2 + y^2) over the unit circle on\n\
the first quadrant is: %f\n", res);
return 0;
}
How can it be thread safe?
NOTE: I know that 1000 threads is not a good way to solve this problem, but I really really want to know how to write thread-safe c programs.
Compile the above program with
gcc ./integral0.c -lpthread -lm -o integral
pthread_mutex_lock(&my_mutex);
// code to make thread safe
pthread_mutex_unlock(&my_mutex);
Declare my_mutex either as a global variable like pthread_mutex_t my_mutex;. Or initialize in code using pthread_mutex_t my_mutex; pthread_mutex_init(&my_mutex, NULL);. Also don't forget to include #include <pthread.h> and link your program with -lpthread when compiling.
The question (in a comment in the code):
// mutex? futex? lock? semaphore? other?
Answer: mutex.
See pthread_mutex_init, pthread_mutex_lock, and pthread_mutex_unlock.

How do we extend the program from 4 to 8 threads in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have started learning C in Uni, and now I'm stuck on posix threads. I have a program that has a single thread, 2 threads and 4 threads as an example from lecture. I need your help to extend this program from 4 to 8/16/32 and how it will perform a difference or not?
Thank you in advance.
Here is the code for 4 thread programm:
/****************************************************************************
This program finds groups of three numbers that when multiplied together
equal 98931313. Compile with:
cc -o factorise4 factorise4.c -lrt -pthread
Kevan Buckley, University of Wolverhampton, October 2012
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <math.h>
#define goal 98931313
typedef struct arguments {
int start;
int n;
} arguments_t;
void factorise(int n) {
pthread_t t1, t2, t3, t4;
//1st pthread
arguments_t t1_arguments;
t1_arguments.start = 0;
t1_arguments.n = n;
//2nd pthread
arguments_t t2_arguments;
t2_arguments.start = 250;
t2_arguments.n = n;
//3rd pthread
arguments_t t3_arguments;
t3_arguments.start = 500;
t3_arguments.n = n;
//4th pthread
arguments_t t4_arguments;
t4_arguments.start = 750;
t4_arguments.n = n;
void *find_factors();
//creating threads
pthread_create(&t1, NULL, find_factors, &t1_arguments);
pthread_create(&t2, NULL, find_factors, &t2_arguments);
pthread_create(&t3, NULL, find_factors, &t3_arguments);
pthread_create(&t4, NULL, find_factors, &t4_arguments);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_join(t4, NULL);
}
//Using 3 loops, 1 loop represents one value that we need to find, and go throught it until 98931313 not will be find.
void *find_factors(arguments_t *args){
int a, b, c;
for(a=args->start;a<args->start+250;a++){
for(b=0;b<1000;b++){
for(c=0;c<1000;c++){
if(a*b*c == args->n){
printf("solution is %d, %d, %d\n", a, b, c);// Printing out the answer
}
}
}
}
}
// Calculate the difference between two times.
long long int time_difference(struct timespec *start, struct timespec *finish, long long int *difference) {
long long int ds = finish->tv_sec - start->tv_sec;
long long int dn = finish->tv_nsec - start->tv_nsec;
if(dn < 0 ) {
ds--;
dn += 1000000000;
}
*difference = ds * 1000000000 + dn;
return !(*difference > 0);
}
//Prints elapsed time
int main() {
struct timespec start, finish;
long long int time_elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
factorise(goal); //This is our goal = 98931313
clock_gettime(CLOCK_MONOTONIC, &finish);
time_difference(&start, &finish, &time_elapsed);
printf("Time elaipsed was %lldns or %0.9lfs\n", time_elapsed, (time_elapsed/1.0e9));
return 0;
}
I'll give you a hint:
If you call a function twice manually, you can put its results into two separate variables:
int y0 = f(0);
int y1 = f(1);
You as well can put them into one array:
int y[2];
y[0] = f(0);
y[1] = f(1);
Or into a memory area on heap (obtained via malloc()):
int * y = malloc(2 * sizeof(*y));
y[0] = f(0);
y[1] = f(1);
In the latter two cases, you can replace the two function calls with
for (i = 0; i < 2; i++) {
y[i] = f(i);
}
Another hint:
For a changed number of threads, you will as well have to change your parameter set.
And another hint:
Thread creation, in your case, can be put into a function:
void facthread_create(pthread_t * thread, int start, int n)
{
arguments_t arguments;
arguments.start = start;
arguments.n = n;
void *find_factors();
//creating thread
pthread_create(thread, NULL, find_factors, &arguments);
}
But - there is a caveat: we have a race condition here. As soon as the thread starts, we can return and the stack space occupied by arguments is freed. So we use an improved version here which is useful for cooperation:
We add a field to arguments_t:
typedef struct arguments {
char used;
int start;
int n;
} arguments_t;
We set used to 0:
void facthread_create(pthread_t * thread, int start, int n)
{
arguments_t arguments;
arguments.start = start;
arguments.n = n;
arguments.used = 0;
void *find_factors();
//creating thread
pthread_create(thread, NULL, find_factors, &arguments);
while (!arguments.used); // wait until thread has "really" started
}
Set used to 1 once the data has safely copied:
void *find_factors(arguments_t *args){
arguments_t my_args = *args; // is this valid? Don't remember... If not, do it element-wise...
*args.used = 1; // Inform the caller that it is safe to continue
int a, b, c;
for(a=my_args.start;a<my_args.start+250;a++){
...
You should get a command line parameter (maybe -t for threads). Then instead of calling factorise from main, have a for loop which does the thread create with the parameter which is calculated from the loop number. Something like:
for (int i = 0; i < threads; i++) {
arguments.start = 250 * i;
arguments.n = n;
pthread_start(...)
}
Note that you should allocate the argument structs before the for loop for clarity.
Let me know if you need more help.
Here is some more help:
0) get the number of threads and the skip (in your case 250) from the command line.
1) create a control stuct which contains the args for the thread, the thread id, etc.
2) using the args, allocate the control struct and fill it in.
3) do a for loop to spawn off the treads.
4) do another for loop to wait for the threads to complete.
For some extra complexity, you could introduce a global variable which any thread could set to signal the other threads that the work is done and they should exit. But don't do this until you get the simple case correct.
If you post some updated code, I will help you some more.

Thread Programming... No output in terminal

I m doing thread programming and trying to implement MonteCarlo technique for calculating Pi value in it. I compiled the code and I have no error but when I execute I get no output for it. Kindly correct me if there's any mistake.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define frand() ((double) rand() / (RAND_MAX))
#define MAX_LEN 1353
const size_t N = 4;
float circlePoints=0;
void* point_counter(void *param){
float xcord;
float ycord;
while(MAX_LEN){
xcord=frand();
ycord=frand();
float cord = (xcord*xcord) + (ycord*ycord);
if(cord <= 1){
circlePoints++;}
}
}
int main()
{
printf("out");
size_t i;
pthread_t thread[N];
srand(time(NULL));
for( i=0;i <4;++i){
printf("in creating thread");
pthread_create( &thread[i], NULL, &point_counter, NULL);
}
for(i=0;i <4;++i){
printf("in joining thread");
pthread_join( thread[i], NULL );
}
for( i=0;i <4;++i){
printf("in last thread");
float pi = 4.0 * (float)circlePoints /MAX_LEN;
printf("pi is %2.4f: \n", pi);
}
return 0;
}
You're hitting an infinite loop here:
while(MAX_LEN){
Since MAX_LEN is and remains non-zero.
As to why you see no output before that, see Why does printf not flush after the call unless a newline is in the format string?
You have an infinite loop in your thread function:
while(MAX_LEN){
...
}
So all the threads you create never come out that loop.
Also, circlePoints is modified by all the threads which will lead to race condition ( what's a race condition? ) and likely render the value incorrect. You should use a mutex lock to avoid it.
while(any_non_zero_number_which does_not_update)
{
infinite loop //not good unless you intend it that way
}

Poisson arrival distribution function and keep track it

I am trying to create a random "hello world" function based on the poisson arrival. In the code below, I define that the average mean (Lamda) is 5. And I want the time to elapse from 1 - 5 second, and keep track of it.
Based on an opensource project, seagull in this image here and here, I can see that for the same time, but different mean, the more it random occurences of the traffic (in my case, the "hello world"). But for my case, it just getting random sleep time, but the number of Hello World is the same.
How can I achieve the idea based on the images like what I use above. Is this the correct way of doing Poisson distribution for random generator? I saw the algorithm for Poisson based on Knuth
Thank you for the help.. Sorry for my bad english.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <string.h>
#include <time.h>
int poisson(double lambda){
int k=0;
double L=exp(-lambda), p=1;
do {
++k;
p *= rand()/(double)INT_MAX;
} while (p > L);
return --k;
}
int main()
{
int i=0;
int val=0;
time_t timer;
char buffer[25];
struct tm* val_time;
/*For time= 0 until time=10*/
for (i=0; i<10; i++)
{
printf("Hello World\n");
/*To print the time*/
time(&timer);
val_time = localtime(&timer);
strftime(buffer, 25, "%Y:%m:%d%H:%M:%S", val_time);
puts(buffer);
sleep(poisson(2)); /*interarrival process*/
}
}
I think the INT_MAX is in error, make that:
p *= rand()/(double)RAND_MAX;
Also, as long as the loop is bounded at 10, you'll not get more hellos. What do you expect?
Here is my full C++11 (not C!) version of the program:
See it live on https://ideone.com/viZi3 (Note it soft-fails with Time limit exceeded there, because of obvious time-constraints on IdeOne)
#include <iostream>
#include <random>
#include <chrono>
#include <iomanip>
static std::mt19937 rng;
static std::poisson_distribution<int> poisson(2.0);
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::time_point<Clock> Time;
int main()
{
const Time finish_pole = Clock::now() + std::chrono::seconds(10);
for (Time now = Clock::now(); now <= finish_pole; now = Clock::now())
{
std::cout << "Hello World\n";
std::time_t now_c = Clock::to_time_t(now);
#if CXX11_SUPPORT_COMPLETE
std::cout << std::put_time(std::localtime(&now_c), "%F %T") << std::endl;
#else
char buffer[25];
strftime(buffer, 25, "%Y:%m:%d%H:%M:%S", localtime(&now_c));
std::cout << buffer << std::endl;
#endif
sleep(poisson(rng)); /*interarrival process*/
}
}
Given your code, you'll always have message printed 10 times. Seems that you need to check if your total time elapsed at the start of loop, and if so, break loop. To give you an idea:
time_t before, timer;
...
time(&before);
for (...) {
time(&timer);
if (time - before > timeout) {
break;
}
before = timer;
...
}

Resources