int main (int argc, char* argv[]){
    int nodecount, *num_in_links, *num_out_links;

    int err = get_node_stat(&nodecount, &num_in_links, &num_out_links);
    if (err != 0) {
        return err;
    }

    node_t *nodehead;
    err = node_init(&nodehead, num_in_links, num_out_links, 0, nodecount);
    if (err != 0) {
        return err;
    }

    double start, end;

    GET_TIME(start);
    double damp_const = (1.0 - DAMPING_FACTOR) / nodecount;
    double *r = init_result_vector(nodecount, false);
    double *r_pre = init_result_vector(nodecount, true);
    page_rank(r, r_pre, num_out_links, num_in_links, nodecount, nodehead, damp_const);
    free(r_pre);
    GET_TIME(end);

    double delay = end - start;
    Lab4_saveoutput(r, nodecount, delay);

    node_destroy(nodehead, nodecount);
    free(num_in_links);
    free(num_out_links);
    free(r);
}
Ejemplo n.º 2
0
int main(int argc, char* argv[]) {

    if (argc != 2)
        fprintf(stderr, "Usage: Requires number of threads.");

    thread_count = atoi(argv[1]);

    Lab3LoadInput(&A, &size);
    x = CreateVec(size);

    double start, end;
    int i = 0;

    GET_TIME(start);
    # pragma omp parallel num_threads(thread_count) \
    shared(A)
    {
        gaussian_elimination();
        jordan_elimination();

        # pragma omp for
        for (i = 0; i < size; ++i) {
            x[i] = A[i][size] / A[i][i];
        }
    }

    GET_TIME(end);

    Lab3SaveOutput(x, size, end-start);
    printf("time is: %e\n", end-start);

    DestroyVec(x);
    DestroyMat(A, size);
    return EXIT_SUCCESS;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[]){ 

	int t; //result;
	double inicio, fim, delta1; //delta2, delta3;
	FILE *arquivo;
	char nomeArquivo[100];

	// Parte de Inicialização
	
	GET_TIME(inicio);
	
	//Validando e recebendo a entrada
	if(argc < 2) {
		printf("Use: %s <arquivo entrada>\n", argv[0]);
		exit(EXIT_FAILURE);
  	}
	

	
	arquivo =fopen("");

	//Alocando memoria e inicializando o vetor da entrada
	vet = malloc (sizeof(float) * tam);

	if(vet==NULL) {
		printf("--ERRO: malloc()\n"); exit(-1);
	}

	for(t=0; t<tam; t++) {
		vet[t] = t;
	}

	GET_TIME(fim);

  	delta1 = fim - inicio;
  	
  	
	/*int mat1[3][3]={{3,0,2},{9,1,7},{1,0,1}};
	int mat2[3][3]={{1,0,-2},{-2,1,-3},{-1,0,3}};
	int mat3[3][3];
	int M1L=3, M2C=3;
	
	for(linha=0; linha<M1L; linha++){
		for(coluna=0; coluna<M2C; coluna++){
			result=0;
		for(i=0; i<M1L; i++) result+=mat1[linha][i]*mat2[i][coluna];
			mat3[linha][coluna]=result;
    	}
    }

	for(linha=0; linha<M1L; linha++){
		for(coluna=0; coluna<M2C; coluna++)
			printf("%d ", mat3[linha][coluna]);
		printf("\n");
	}*/
	
	printf("Tempo inicializacoes: %.8lf\n", delta1);
	return 0;
  
}
Ejemplo n.º 4
0
int main(int argc, char* argv[]) {
   pthread_t* thread_handles;
   long thread;
   double start, finish;

   if (argc != 3) Usage(argv[0]);
   thread_count = strtol(argv[1], NULL, 10);
   n = strtol(argv[2], NULL, 10);

   thread_handles = malloc(thread_count*sizeof(pthread_t));
   sem_init(&my_semaphore, 0, 1);

   GET_TIME(start);
   for (thread = 0; thread < thread_count; thread++)
      pthread_create(&thread_handles[thread], NULL, Lock_and_unlock,
            (void*) thread);

   for (thread = 0; thread < thread_count; thread++)
      pthread_join(thread_handles[thread], NULL);
   GET_TIME(finish);

   printf("Total number of times my_semaphore was locked and unlocked: %d\n",
         total);
   printf("Elapsed time = %e seconds\n", finish-start);

   sem_destroy(&my_semaphore);

   free(thread_handles);
   return 0;
}  /* main */
Ejemplo n.º 5
0
/*--------------------------------------------------------------------*/
int main(int argc, char* argv[]) {
   long       thread, i;
   pthread_t* thread_handles; 
   double start, finish;

   if (argc != 2)
      Usage(argv[0]);
   thread_count = strtol(argv[1], NULL, 10);

   thread_handles = malloc (thread_count*sizeof(pthread_t));
   for (i = 0; i < BARRIER_COUNT; i++)
      barrier_thread_counts[i] = 0;
   pthread_mutex_init(&barrier_mutex, NULL);

   GET_TIME(start);
   for (thread = 0; thread < thread_count; thread++)
      pthread_create(&thread_handles[thread], NULL,
          Thread_work, (void*) thread);

   for (thread = 0; thread < thread_count; thread++) {
      pthread_join(thread_handles[thread], NULL);
   }
   GET_TIME(finish);
   printf("Elapsed time = %e seconds\n", finish - start);

   pthread_mutex_destroy(&barrier_mutex);
   free(thread_handles);
   return 0;
}  /* main */
int main(int argc, char* argv[])
{
long i; 
int key, success, attempts;
pthread_t* thread_handles;
int inserts_in_main;
unsigned seed = 1;
double inicio, fin;

if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10);
Get_input(&inserts_in_main);

i = attempts = 0;
pthread_mutex_init(&head_mutex, NULL);
while ( i < inserts_in_main && attempts < 2*inserts_in_main )
{
   key = my_rand(&seed) % MAX_KEY;
   success = Insert(key);
   attempts++;
   if (success) i++;
}
printf("%ld keys insertadas\n", i);

#  ifdef OUTPUT
   printf("Antes de crear hilos, lista = \n");
   Print();
   printf("\n");
#  endif

thread_handles = malloc(thread_count*sizeof(pthread_t));
pthread_mutex_init(&count_mutex, NULL);

GET_TIME(inicio);
for (i = 0; i < thread_count; i++)
   pthread_create(&thread_handles[i], NULL, Thread_work, (void*) i);

for (i = 0; i < thread_count; i++)
   pthread_join(thread_handles[i], NULL);
GET_TIME(fin);
printf("Tiempo de ejecución = %e segundos\n", fin - inicio);
printf("Total operaciones = %d\n", total_ops);
printf("Operaciones miembro = %d\n", total_miembro);
printf("Operaciones insertar = %d\n", total_insertar);
printf("Operaciones borrado = %d\n", total_borrado);

#  ifdef OUTPUT
   printf("Despues de terminar los hilos, lista = \n");
   Print();
   printf("\n");
#  endif

Free_list();
pthread_mutex_destroy(&head_mutex);
pthread_mutex_destroy(&count_mutex);
free(thread_handles);

return 0;
}
Ejemplo n.º 7
0
Archivo: main.c Proyecto: chen-fang/HPC
void* Trapezoid( void* rank )
{

   double start = 0.0;
   double end = 0.0;
   
   sem_wait( &sem_count );
   if( counter != thread_count - 1 )
   {
      counter++;
      sem_post( &sem_count );
      sem_wait( &sem_barrier );
   }
   else
   {
      counter = 0;
      sem_post( &sem_count );
      long i;      
      for( i = 0; i < thread_count-1; i++ )
	 sem_post( &sem_barrier );
   }

   GET_TIME( start );

   
   double h = (b-a) / n;
   long my_rank = (long)rank;
   long   local_n = n / thread_count;
   double local_a = a + my_rank * local_n * h;
   double local_b = local_a + local_n * h;

   double my_sum = ( F(local_a) + F(local_b) ) / 2.0;
   long i;
   for( i = 1; i < local_n; i++ )
   {
      double x;
      x = local_a + i * h;
      my_sum += F(x);
   }
   my_sum *= h;


   GET_TIME( end );
   double elapsed = end - start;

   sem_wait( &sem_timer );
   printf( "%2ld |  Elapsed time = %e\n", my_rank, elapsed );
   if( elapsed > max_elapsed )
      max_elapsed = elapsed;
   sem_post( &sem_timer );

   sem_wait( &sem_sum );
   printf( "Add from rank # %ld  |  my_sum = %10.6f\n", my_rank, my_sum );
   sum += my_sum;
   
   sem_post( &sem_sum );

   return NULL;
}
Ejemplo n.º 8
0
/**
 * Conversion function. They deal with data-types in 3 ways, always making local copies.
 * In order to allow performance testings, there are 3 functions:
 *  - one copying directly from one memory location to another one using the
 *    data-type copy function.
 *  - one which use a 2 convertors created with the same data-type
 *  - and one using 2 convertors created from different data-types.
 *
 */
static int local_copy_ddt_count( opal_datatype_t const * const pdt, int count )
{
    OPAL_PTRDIFF_TYPE lb, extent;
    size_t malloced_size;
    char *odst, *osrc;
    void *pdst, *psrc;
    TIMER_DATA_TYPE start, end;
    long total_time;
    int errors = 0;

    malloced_size = compute_memory_size(pdt, count);
    opal_datatype_get_extent( pdt, &lb, &extent );

    odst = (char*)malloc( malloced_size );
    osrc = (char*)malloc( malloced_size );

    {
        for( size_t i = 0; i < malloced_size; i++ )
            osrc[i] = i % 128 + 32;
        memcpy(odst, osrc, malloced_size);
    }
    pdst = odst - lb;
    psrc = osrc - lb;

    cache_trash();  /* make sure the cache is useless */

    GET_TIME( start );
    if( OPAL_SUCCESS != opal_datatype_copy_content_same_ddt( pdt, count, pdst, psrc ) ) {
        printf( "Unable to copy the datatype in the function local_copy_ddt_count."
                " Is the datatype committed ?\n" );
    }
    GET_TIME( end );
    total_time = ELAPSED_TIME( start, end );
    printf( "direct local copy in %ld microsec\n", total_time );
    if(outputFlags & VALIDATE_DATA) {
        for( size_t i = 0; i < malloced_size; i++ ) {
            if( odst[i] != osrc[i] ) {
                printf("error at position %lu (%d != %d)\n",
                       (unsigned long)i, (int)(odst[i]), (int)(osrc[i]));
                errors++;
                if(outputFlags & QUIT_ON_FIRST_ERROR) {
                    opal_datatype_dump(pdt);
                    assert(0); exit(-1);
                }
            }
        }
        if( 0 == errors ) {
            printf("Validation check succesfully passed\n");
        } else {
            printf("Found %d errors. Giving up!\n", errors);
            exit(-1);
        }
    }
    free( odst );
    free( osrc );

    return (0 == errors ? OPAL_SUCCESS : errors);
}
Ejemplo n.º 9
0
// Rotina Principal do programa
int main(int argc, char **argv) {

  double start, finish;
  int i;

  if(argc != 2){
    printf("Usage: %s <number of particles>\n",argv[0]);
    return 0;
  }

  // Recebe o número de partículas que devem ser processadas
  // e posteriormente renderizadas
  nParticulas = atoi(argv[1]);

  // Define a quantidade de partículas que não estão no chão (inicialmente nenhuma delas está)
  nParticulasAux = nParticulas;

  // Define posição inicial das particulas
  iniciarParticula();

  // Funções necessárias para inicializar o OpenGL
  // e criar a janela que ficará renderizando
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
  glutInitWindowPosition(100,100);
  glutInitWindowSize(640,640);
  glutCreateWindow("Trabalho Final - Computação Paralela");
  glEnable(GL_DEPTH_TEST);

  // Inicializa a contagem do tempo
  GET_TIME(start);

  // Registrando CallBacks
  glutDisplayFunc(renderScene);
  glutReshapeFunc(changeSize);
  glutIdleFunc(renderScene);

  // Função que mantém o loop do evento de renderização
  // funcionado
  // Foi escolhido a função glutMainLoopEvent ao invés de glutMainLoop
  // pelo simples fato de que a segunda não pára até o programa finalizar
  // e a que escolhemos funciona como apenas uma iteração dessa função
  while(!Flag)
  {
    glutMainLoopEvent();
    renderScene();
  }

  // Finaliza o timer
  GET_TIME(finish);

  // Printa o tempo
  printf("Tempo gasto: %f\n", (finish - start));

  free(vetor2);

  return 1;
}
Ejemplo n.º 10
0
int main(int argc, char * argv[]){
	int threads = parse_number_threads(argc, argv);
	double **A; int size; 
    Lab3LoadInput(&A, &size);
    double storage[size];

    // Initialize Times
	double start_time;
	double end_time;
	GET_TIME(start_time);


 	int k;
 	for (k = 0; k < size; k++){
 		int max_indice = find_max_indice(k, A, size);
 		swap_rows(A, k, max_indice);

 		int i;
 		int j;
		//printf("Current k value: %d \n",k);
		//printf("----------------------------\n");
 		for (i = k+1; i < size; i++){
		//printf("Current Row: %d \n",i);
			double subtrahend_coefficient = (A[i][k]/A[k][k]);
			//printf("Subtrahend Coefficient: %f \n",subtrahend_coefficient);
 			for (j = k; j < size + 1; j++){
				//printf("Current Col: %d \n",j);
 				A[i][j] = A[i][j] - (subtrahend_coefficient* A[k][j]);
 			}
 		}
 	}

 	//Lab2_saveoutput(A, size, 10, "Gauss.txt");

 	
 	for (k = size-1; k > 0; k--){
		int i;
 		for (i = 0; i < k; i++){
 			//double result = A[i][size] - ( (A[i][k] / A[k][k]) * A[k][size]);;
 			//printf("A[%d][%d] = %f \n", i, size, result);
 			A[i][size] = A[i][size] - ( (A[i][k] / A[k][k]) * A[k][size]);
 			A[i][k] = A[i][k] - ( (A[i][k] / A[k][k]) * A[k][k]);
 		}
 	}

 	//Lab2_saveoutput(A, size, 10, "Jordan.txt");


 	// Retrieve elapsed time
	GET_TIME(end_time);

	get_result(storage, A, size);
	printf("Total Time: %f \n",end_time-start_time);
 	Lab3SaveOutput(storage, size, end_time - start_time);

	return 0;
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
    int i;
    int model, model_min, model_max;
    testobj_t *keep_arr;

    GC_INIT();
    GC_init_finalized_malloc();

    keep_arr = GC_MALLOC(sizeof(void *)*KEEP_CNT);

    if (argc == 2 && strcmp(argv[1], "--help") == 0) {
        fprintf(stderr,
                "Usage: %s [FINALIZATION_MODEL]\n"
                "\t0 -- original finalization\n"
                "\t1 -- finalization on reclaim\n"
                "\t2 -- no finalization\n", argv[0]);
        return 1;
    }
    if (argc == 2) {
        model_min = model_max = atoi(argv[1]);
        if (model_min < 0 || model_max > 2)
            exit(2);
    }
    else {
        model_min = 0;
        model_max = 2;
    }

    printf("\t\t\tfin. ratio       time/s    time/fin.\n");
    for (model = model_min; model <= model_max; ++model) {
        double t = 0.0;
        free_count = 0;

#       ifdef CLOCK_TYPE
            CLOCK_TYPE tI, tF;
            GET_TIME(tI);
#       endif
        for (i = 0; i < ALLOC_CNT; ++i) {
            int k = rand() % KEEP_CNT;
            keep_arr[k] = testobj_new(model);
        }
        GC_gcollect();
#       ifdef CLOCK_TYPE
            GET_TIME(tF);
            t = MS_TIME_DIFF(tF, tI)*1e-3;
#       endif

        if (model < 2)
            printf("%20s: %12.4lf %12lg %12lg\n", model_str[model],
                   free_count/(double)ALLOC_CNT, t, t/free_count);
        else
            printf("%20s: %12.4lf %12lg %12s\n",
                   model_str[model], 0.0, t, "N/A");
    }
    return 0;
}
Ejemplo n.º 12
0
int main(int argc, char **argv) 
{
	int 			correctsum=0, result = 0;
	pthread_t 		tid[MAXTHREADS];
	int 			i, myid[MAXTHREADS];
	struct timespec 	t0, t1, t2, t3;
	unsigned long 	sec, nsec;
	float 		comp_time, total_time; 	// in milli seconds

	GET_TIME(t0);
    	if (argc != 2) {
		printf("Usage: %s <numthreads>\n", argv[0]);
		exit(0);
    	}
    	numthreads = atoi(argv[1]);
    	if (numthreads > MAXTHREADS) {
		printf("numthreads > MAXTHREADS (%d)\n", MAXTHREADS);
		exit(0);
    	}
    	for (i=0; i < N; i++) {
    		vector[i] = i % 3; // also test with random() % 3;
    		correctsum += vector[i];
    	}
	GET_TIME(t1);
  	//total_time = elapsed_time_msec(&t0, &t1, &sec, &nsec);
  	//printf("InitTime(ms)=%8.1f: ", total_time);
    	for (i = 0; i < numthreads; i++) {                  
		myid[i] = i; 
		psum[i] = 0;                                 
		pthread_create(&tid[i], NULL, sum, &myid[i]); 
    	}                                                 
    	for (i = 0; i < numthreads; i++)  {                  
		pthread_join(tid[i], NULL);                   
    	}
	GET_TIME(t2);

    	// For checking: add up the partial sums computed by each thread 
	for (i = 0; i < numthreads; i++)                    
		result += psum[i];
	correctsum = REPEAT * correctsum;  
   	if (result != correctsum || (correctsum != sumtotal)  )
		printf("# Error! : correctsum=%d, result=%d, sumtotal=%d\n", correctsum, result, sumtotal); 
	GET_TIME(t3);
  	comp_time = elapsed_time_msec(&t1, &t2, &sec, &nsec);
  	total_time = elapsed_time_msec(&t0, &t3, &sec, &nsec);
	#ifdef BAD_FS
	if (numthreads == 1) {
		printf("# PSumVector: Good   : N=%d : Threads=%d : CompTime(ms)=%.2f : CompTime/TotalTime=%.1f%%\n", \
			N, numthreads, comp_time, 100.0*comp_time/total_time);
		return 0;
	}
	#endif
	printf(MSG, N, numthreads, comp_time, 100.0*comp_time/total_time);

	return 0;
}
Ejemplo n.º 13
0
int calculate(double *r, node *A) {
    int i, j;
    double *r_pre;
    double damp_const;
    damp_const = (1.0 - DAMPING_FACTOR) / n;
    int my_rank, comm_sz, local_n;
    double start = 0, end = 0; // for time

    MPI_Init(NULL, NULL);

    /* Get my process rank */
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    /* Find out how many processes are being used */
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);

    r_pre = malloc(n * sizeof(double));

    local_n = n / comm_sz;

    double still_err = 1;
    double *local_r = malloc(local_n * sizeof(double));

    if (my_rank == 0) {
        GET_TIME(start);
    }
    while (still_err > EPSILON) {
        backup_vec(r, r_pre, n);
        for ( i = local_n * my_rank; i < local_n * (my_rank + 1); i++) {
            local_r[i - local_n * my_rank] = 0.0;
            for ( j = 0; j < A[i].size_Di; ++j) {
                local_r[i - local_n * my_rank] += r_pre[A[i].Di[j]] / A[A[i].Di[j]].li;
            }
            local_r[i - local_n * my_rank] *= DAMPING_FACTOR;
            local_r[i - local_n * my_rank] += damp_const;
        }
        MPI_Gather(local_r, local_n, MPI_DOUBLE, r, local_n, MPI_DOUBLE, 0, MPI_COMM_WORLD);
        if (my_rank == 0) {
            still_err = rel_err(r, r_pre, n);
        }
        MPI_Bcast(&still_err, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
        MPI_Bcast(r, n, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    }
    if (my_rank == 0) {
        GET_TIME(end);
        printf("%f\n", end-start);
        Lab4_saveoutput(r, n, end-start);
    }

    free(r_pre);

    MPI_Finalize();

    return 0;
}
Ejemplo n.º 14
0
int main(int argc, char **argv)
{
    int totalcount=0, numthreads, i;
    pthread_t 	main_tid, tid[MAXTHREADS];
    int 	myid[MAXTHREADS];
    struct timespec 	t0, t1, t2, t3;
    unsigned long 	sec, nsec;
    float 		comp_time, total_time; 	// in milli seconds
    
    	GET_TIME(t0);
    	if (argc != 2) {			//if the number of threads in not specified
		printf("Usage: %s <num_threads> (max threads = %d)\n", argv[0],MAXTHREADS);
		exit(0);
    	}

    	numthreads = atoi(argv[1]);		//convert number of threads into int

    	if (numthreads > MAXTHREADS) {		//print number of threads
		printf("nthreads > MAXTHREADS (16)\n");
		exit(0);
    	}
    
    sem_init(&mutexA, 0, 1);      
    sem_init(&mutexB, 0, 1); 
    
    GET_TIME(t1);
    
    for (i = 0; i < numthreads; i++) {  	                
	myid[i] = i;
	pthread_create(&tid[i], NULL, (void *) &handler, &myid[i]); 
    }   
    
    for (i = 0; i < numthreads; i++)  {                  
	pthread_join(tid[i], NULL);                   
    }
    
    GET_TIME(t2);	
                                                              
    sem_destroy(&mutexA);
    sem_destroy(&mutexB);
    
    if(counter1 != counter2){
       printf("# Error! : counter1(%d) != counter2(%d) \n", counter1, counter2);
    }
    
    GET_TIME(t3);
    
    comp_time = elapsed_time_msec(&t1, &t2, &sec, &nsec);
    total_time = elapsed_time_msec(&t0, &t3, &sec, &nsec);
    
     printf(MSG, N, numthreads, comp_time, 100.0*comp_time/total_time);
                   
    return 0;
} 
Ejemplo n.º 15
0
/* returns TME_FALSE if the entry is not found    */
uint32 normal_lut_wo_insert(uint8 *key, TME_DATA *data, MEM_TYPE *mem_ex, struct time_conv *time_ref) 
{
	uint32 i;
	uint32 tocs=0;
	uint32 *key32=(uint32*) key;
	uint32 shrinked_key=0;
	uint32 index;
	RECORD *records=(RECORD*)data->lut_base_address;
	uint8 *offset;
	uint32 key_len=data->key_len;
	/*the key is shrinked into a 32-bit value */	
	for (i=0; i<key_len;i++) 
		shrinked_key^=key32[i];
    /*the first index in the table is calculated*/
	index=shrinked_key % data->lut_entries;

	while (tocs<=data->filled_entries)
	{ 	

		if (records[index].block==0)
		{   /*out of table, insertion is not allowed*/
			GET_TIME((struct timeval *)(data->shared_memory_base_address+4*key_len),time_ref);
			data->last_found=NULL;	
			return TME_FALSE;
		}
		/*offset contains the absolute pointer to the block*/
		/*associated with the current entry */
		
		offset=mem_ex->buffer+SW_ULONG_AT(&records[index].block,0);		

		for (i=0; (i<key_len) && (key32[i]==ULONG_AT(offset,i*4)); i++);
		
		if (i==key_len)
			{
				/*key in the block matches the one provided, right entry*/
				GET_TIME((struct timeval *)(offset+4*key_len),time_ref);
				data->last_found=(uint8*)&records[index];
				return TME_TRUE;
			}
		else 
		{
			/*wrong entry, rehashing*/
			index=(index+data->rehashing_value) % data->lut_entries;
			tocs++;
		}
	}

	/*nothing found, last found= out of lut*/
	GET_TIME((struct timeval *)(data->shared_memory_base_address+4*key_len),time_ref);
	data->last_found=NULL;
	return TME_FALSE;

}
Ejemplo n.º 16
0
/*------------------------------------------------------------------*/
int main(int argc, char* argv[]) {
   long       thread;
   pthread_t* thread_handles;
   double start, finish;

   if (argc != 4) Usage(argv[0]);
   thread_count = strtol(argv[1], NULL, 10);
   m = strtol(argv[2], NULL, 10);
   n = strtol(argv[3], NULL, 10);

#  ifdef DEBUG
   printf("thread_count =  %d, m = %d, n = %d\n", thread_count, m, n);
#  endif

   thread_handles = malloc(thread_count*sizeof(pthread_t));
   sem_init(&sem, 0, 1); /* Initial value is 1 */
   A = malloc(m*n*sizeof(double));
   x = malloc(n*sizeof(double));
   y = malloc(m*sizeof(double));
   
   srandom(1);
   Gen_matrix(A, m, n);
#  ifdef DEBUG
   Print_matrix("We generated", A, m, n); 
#  endif

   Gen_vector(x, n);
#  ifdef DEBUG
   Print_vector("We generated", x, n); 
#  endif

   GET_TIME(start);
   for (thread = 0; thread < thread_count; thread++)
      pthread_create(&thread_handles[thread], NULL,
         Pth_mat_vect, (void*) thread);

   for (thread = 0; thread < thread_count; thread++)
      pthread_join(thread_handles[thread], NULL);
   GET_TIME(finish);

#  ifdef DEBUG
   Print_vector("The product is", y, m); 
#  endif
   printf("Elapsed time = %e seconds\n", finish - start);

   free(A);
   free(x);
   free(y);
   sem_destroy(&sem);
   free(thread_handles);

   return 0;
}  /* main */
Ejemplo n.º 17
0
int main (int argc, char *argv[]){
	MPI_Comm comm;
	int p, my_rank;
	long long int n;
	long long int local_n;
	float ans=0;
	long long int in_circle=0;
	double start, finish, elapsed;
	float pi,err;



	MPI_Init(&argc, &argv);
	comm = MPI_COMM_WORLD;
	MPI_Comm_size(comm, &p);
	MPI_Comm_rank(comm, &my_rank);

	if (my_rank == 0){
		if (argc>1) {
			n = strtol(argv[1], NULL, 10);
		}
		else {
			n = 0;
		}
	}
	MPI_Bcast(&n, 1, MPI_LONG_LONG, 0, comm);
	if (n <= 0){
		if (my_rank == 0){
			printf("Enter the value for n: mpiexec -n <number of nodes> "); 
			printf("./mpi_monte_carlo_pi <value for n>. \nProgram will Terminate\n");
		}
		MPI_Finalize();
	}

	GET_TIME(start);
	local_n = n/p;
	in_circle = monte_carlo_pi(local_n, my_rank, in_circle);
	ans = global_calc(n, in_circle, my_rank, comm, p, ans);
	pi = pi_val();
	err = pi - ans;
	GET_TIME(finish);
	elapsed = finish-start;

	if (my_rank ==0){
		printf ("Estimated Value of Pi for %lld 'darts': %f\n",n,ans);
		printf ("Actual Value of Pi: %f\n", pi);
		printf ("Difference between Estimated and Actual: %f\n",err);
		printf ("Time: %f\n", elapsed);
	}

	MPI_Finalize();
	return 0;
}
Ejemplo n.º 18
0
int main(int argc, char **argv) 
{
	int 			i, result = 0;
	pthread_t 		main_tid, tid[MAXTHREADS];
	int 			myid[MAXTHREADS], status;
	struct timespec 	t0, t1, t2, t3;
	unsigned long 	sec, nsec;
	float 		comp_time, total_time; 	// in milli seconds
	
	GET_TIME(t0);
    	if (argc != 2) {
		printf("Usage: %s <num_threads> (max threads = 16)\n", argv[0]);
		exit(0);
    	}
    	numthreads = atoi(argv[1]);
    	if (numthreads > MAXTHREADS) {
		printf("nthreads > MAXTHREADS (16)\n");
		exit(0);
    	}
	for (i=0; i< N; i++) 
		x[i] = random();		// not optimized
	
	GET_TIME(t1);
  	//total_time = elapsed_time_msec(&t0, &t1, &sec, &nsec);
  	//printf("InitTime(ms)=%8.1f: ", total_time);
    	for (i = 0; i < numthreads; i++) {                  
		myid[i] = i;
		count[i] = 0;
		pthread_create(&tid[i], NULL, pcount, &myid[i]); 
    	}                                                 
    	for (i = 0; i < numthreads; i++)  {                  
		pthread_join(tid[i], NULL);                   
    	}

	GET_TIME(t2);
	for (i=0; i < numthreads; i++)
		result += count[i];
	if (result != totalcount) printf("# Error! : result(%d) != totalcount(%d)\n", result, totalcount);
	GET_TIME(t3);
  	comp_time = elapsed_time_msec(&t1, &t2, &sec, &nsec);
  	total_time = elapsed_time_msec(&t0, &t3, &sec, &nsec);
	#ifdef BAD_FS
	if (numthreads == 1) {
		printf("# PCount: Good   : N=%d : Threads=%d : CompTime(ms)=%.2f : CompTime/TotalTime=%.1f%%\n", \
			N, numthreads, comp_time, 100.0*comp_time/total_time);
		return 0;
	}
	#endif
	printf(MSG, N, numthreads, comp_time, 100.0*comp_time/total_time);
    	//pthread_exit(NULL);
    	return 0;
}
Ejemplo n.º 19
0
int main(int argc, char* argv[]) {
    long thread_i;
    pthread_t* thread_handles;
    double start, end;

    if (argc != 2) {
        fprintf(stderr, "Please indicate the number of threads!\n");
        exit(EXIT_FAILURE);
    }
    thread_count_ = strtol(argv[1], NULL, 10);

    thread_handles = malloc(thread_count_ * sizeof *thread_handles);

    Lab2_loadinput(&dp_, &city_count_);

    int i, j, k;
    sem_array = malloc(city_count_ * sizeof *sem_array);

    for (i = 0; i < city_count_; ++i) {
        sem_array[i] = malloc(city_count_ * sizeof *sem_array[i]);
        for (j = 0; j < city_count_; ++j) {
            sem_array[i][j] = malloc(city_count_ * sizeof *sem_array[i][j]);
            for (k = 0; k < city_count_; ++k) {
                sem_init(&sem_array[i][j][k],
                         0, // shared == 0; shared between threads
                         0);// init_value is set to zero
            } 
        }
    }


    for (i = 0; i < city_count_; ++i) {
        for (j = 0; j < city_count_; ++j) {
            sem_post(&sem_array[i][j][0]);
        }
    }

    GET_TIME(start);
    for (thread_i = 0; thread_i < thread_count_; ++thread_i)
        pthread_create( &thread_handles[thread_i], 
            NULL, 
            thread_subcal, 
            (void*)thread_i);
    for (thread_i = 0; thread_i < thread_count_; ++thread_i)
        pthread_join(thread_handles[thread_i], NULL);
    GET_TIME(end);

    Lab2_saveoutput(dp_, city_count_, end-start);
    printf("Time taken: %f\n", end-start);
    return EXIT_SUCCESS;
}
Ejemplo n.º 20
0
void* pthread_mul_matrix(void* _tid) {
	int tid = *((int*) _tid);

	double start;
	double finish;

	GET_TIME(start);
	multiply_matrix(tid);
	GET_TIME(finish);

	printf("Thread_%02d,%lf,%lf\n", tid, start - start_time, finish - start_time);
	//printf("Thread: %d finish - %lf\n", tid, finish - start_time);
	return NULL;
}
Ejemplo n.º 21
0
int main(int argc, char** argv){
	if(argc > 1) {
		matrix_size = atoi(argv[1]);
	}
	else {
		matrix_size = 3;
	}

	srand(time(NULL));

	alloc_matrices();


	init_matrix(matrix_a);
	init_matrix(matrix_b);

	pthread_t* threads = (pthread_t*) malloc(matrix_size * sizeof(pthread_t));
	int* tids = (int*) malloc(matrix_size * sizeof(int));

	double start;
	double finish;
	double elapsed;

	GET_TIME(start);
	start_time = start;

	for(int thread_id = 0; thread_id < matrix_size; thread_id++) {
		tids[thread_id] = thread_id;
		pthread_create(threads + thread_id, NULL, pthread_mul_matrix, (void*) (tids + thread_id));
	}

	for(int thread_id = 0; thread_id < matrix_size; thread_id++) {
		pthread_join(threads[thread_id], NULL);
	}

	GET_TIME(finish);
	elapsed = finish - start;

	//printf("%lf\n", elapsed);
	// printf("A = ");
	// print_matrix(matrix_a);
	// printf("B = ");
	// print_matrix(matrix_b);
	// printf("C = ");
	// print_matrix(matrix_c);

	// puts("A * B - C");

    return 0;
}
Ejemplo n.º 22
0
int main(int argc, char* argv[]) {
   char       greeting[MAX_STRING];  /* String storing message */
char       received_greet[MAX_STRING];  /* String storing message */
   int        comm_sz;               /* Number of processes    */
   int        my_rank;               /* My process rank        */
   int size;
	double start, finish, elapsed;
   /* Start up MPI */
   MPI_Init(&argc, &argv);

   /* Get the number of processes */
   MPI_Comm_size(MPI_COMM_WORLD, &comm_sz); 

   /* Get my rank among all the processes */
   MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); 

   if (my_rank != 0) { 
      /* Create message */
      //sprintf(greeting, "Greetings from process %d of %d!",my_rank, comm_sz);
      /* Send message to process 0 */
	
	for(size=0;  size<MAX_STRING ; size++){
		greeting[size] = 'x';
		greeting[size+1] = '\0';
		GET_TIME(start);
		MPI_Send(greeting, size, MPI_CHAR, 0, 0,MPI_COMM_WORLD);
		MPI_Recv(received_greet, size, MPI_CHAR, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
		GET_TIME(finish);
		elapsed = finish - start;
		printf("The message (%d sized) to be timed took %e seconds\n",size, elapsed);
	} 
   } else {  
      /* Print my message */
      printf("Greetings from process %d of %d!\n", my_rank, comm_sz);
      
         /* Receive message from process q */
	for(size=0;  size<MAX_STRING ; size++){
		MPI_Recv(received_greet, size, MPI_CHAR, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
		MPI_Send(greeting, size, MPI_CHAR, 1, 0,MPI_COMM_WORLD);		
	}
      
   }

   /* Shut down MPI */
   MPI_Finalize(); 

   return 0;
}  /* main */
Ejemplo n.º 23
0
/*------------------------------------------------------------------*/
int main(int argc, char* argv[]) {
   FILE* digraph_file;
   tour_t tour;
   double start, finish;

   if (argc != 2) Usage(argv[0]);
   digraph_file = fopen(argv[1], "r");
   if (digraph_file == NULL) {
      fprintf(stderr, "Can't open %s\n", argv[1]);
      Usage(argv[0]);
   }
   Read_digraph(digraph_file);
   fclose(digraph_file);
#  ifdef DEBUG
   Print_digraph();
#  endif   
   avail = Init_stack();

   best_tour = Alloc_tour();
   Init_tour(best_tour, INFINITY);
#  ifdef DEBUG
   Print_tour(best_tour, "Best tour");
   printf("City count = %d\n",  City_count(best_tour));
   printf("Cost = %d\n\n", Tour_cost(best_tour));
#  endif
   tour = Alloc_tour();
   Init_tour(tour, 0);
#  ifdef DEBUG
   Print_tour(tour, "Starting tour");
   printf("City count = %d\n",  City_count(tour));
   printf("Cost = %d\n\n", Tour_cost(tour));
#  endif

   GET_TIME(start);
   Iterative_dfs(tour);
   GET_TIME(finish);
   Free_tour(tour);
   
   Print_tour(best_tour, "Best tour");
   printf("Cost = %d\n", best_tour->cost);
   printf("Elapsed time = %e seconds\n", finish-start);

   free(best_tour->cities);
   free(best_tour);
   Free_avail();
   free(digraph);
   return 0;
}  /* main */
Ejemplo n.º 24
0
void   get_cpu_time   (Time* usrT,  Time* sysT)   {
    //
    // Get the user and/or system cpu times in a system independent way.

    time_struct_t   ts;

    GET_TIME(ts);

    if (usrT != NULL) {
	SET_TIME(usrT, USR_TIME(ts));
	if (usrT->seconds < lastU.seconds)
	    usrT->seconds = lastU.seconds;
	if ((usrT->seconds == lastU.seconds) && (usrT->uSeconds < lastU.uSeconds))
	    usrT->uSeconds = lastU.uSeconds;
	lastU = *usrT;
    }

    if (sysT != NULL) {
	SET_TIME(sysT, SYS_TIME(ts));
	if (sysT->seconds < lastS.seconds)
	    sysT->seconds = lastS.seconds;
	if ((sysT->seconds == lastS.seconds) && (sysT->uSeconds < lastS.uSeconds))
	    sysT->uSeconds = lastS.uSeconds;
	lastS = *sysT;
    }
}
Ejemplo n.º 25
0
LRESULT AutoSearchFrame::onAdd(WORD , WORD , HWND , BOOL& ) {
	SearchPageDlg dlg;
	dlg.expireTime = SETTING(AUTOSEARCH_EXPIRE_DAYS) > 0 ? GET_TIME() + (SETTING(AUTOSEARCH_EXPIRE_DAYS)*24*60*60) : 0;
	if(dlg.DoModal() == IDOK) {
		string search = dlg.searchString + "\r\n";
		string::size_type j = 0;
		string::size_type i = 0;
	
		while((i = search.find("\r\n", j)) != string::npos) {
			string str = search.substr(j, i-j);
			j = i +2;
			if(str.size() >= 5) { //dont accept shorter search strings than 5 chars
				AutoSearchPtr as = new AutoSearch(true, str, (SearchManager::TypeModes)dlg.fileType, (AutoSearch::ActionType)dlg.action, dlg.remove, 
					dlg.target, dlg.targetType, (StringMatcher::Type)dlg.matcherType, dlg.matcherString, dlg.userMatch, dlg.searchInterval, dlg.expireTime, dlg.checkQueued, dlg.checkShared);
				as->startTime = dlg.startTime;
				as->endTime = dlg.endTime;
				as->searchDays = dlg.searchDays;
				AutoSearchManager::getInstance()->addAutoSearch(as);
			} else if(search.size() < 5) { // dont report if empty line between/end when adding multiple
				//MessageBox(_T("Not adding the auto search: ") + Text::toT(str).c_str());
				MessageBox(CTSTRING(LINE_EMPTY_OR_TOO_SHORT));
			}
		}
	}
	return 0;
}
Ejemplo n.º 26
0
	SessionPtr WebUserManager::authenticate(const string& aUserName, const string& aPassword, bool aIsSecure, uint64_t aMaxInactivityMinutes, bool aUserSession) noexcept {
		auto u = getUser(aUserName);
		if (!u) {
			return nullptr;
		}

		if (u->getPassword() != aPassword) {
			return nullptr;
		}

		u->setLastLogin(GET_TIME());
		u->addSession();
		fire(WebUserManagerListener::UserUpdated(), u);

		auto uuid = boost::uuids::random_generator()();
		auto session = std::make_shared<Session>(u, boost::uuids::to_string(uuid), aIsSecure, server, aMaxInactivityMinutes, aUserSession);

		{
			WLock l(cs);
			sessionsRemoteId.emplace(session->getAuthToken(), session);
			sessionsLocalId.emplace(session->getId(), session);
		}

		if (aUserSession) {
			ActivityManager::getInstance()->updateActivity();
		}

		return session;
	}
Ejemplo n.º 27
0
bool CryptoManager::checkCertificate(int minValidityDays) noexcept{
	auto x509 = ssl::getX509(SETTING(TLS_CERTIFICATE_FILE).c_str());
	if (!x509) {
		return false;
	}

	ASN1_INTEGER* sn = X509_get_serialNumber(x509);
	if (!sn || !ASN1_INTEGER_get(sn)) {
		return false;
	}

	X509_NAME* name = X509_get_subject_name(x509);
	if (!name) {
		return false;
	}

	string cn = getNameEntryByNID(name, NID_commonName);
	if (cn != ClientManager::getInstance()->getMyCID().toBase32()) {
		return false;
	}

	ASN1_TIME* t = X509_get_notAfter(x509);
	if (t) {
		time_t minValid = GET_TIME() + 60 * 60 * 24 * minValidityDays;
		if (X509_cmp_time(t, &minValid) < 0) {
			return false;
		}
	}
	return true;
}
Ejemplo n.º 28
0
pair<double, bool> ListFilter::prepareTime() const {
    size_t end;
    time_t multiplier;
    auto hasType = [&end, this](string&& id) {
        end = Util::findSubString(matcher.pattern, id, matcher.pattern.size() - id.size());
        return end != string::npos;
    };

    bool hasMatch = true;
    if (hasType("y")) {
        multiplier = 60 * 60 * 24 * 365;
    } else if (hasType("m")) {
        multiplier = 60 * 60 * 24 * 30;
    } else if (hasType("w")) {
        multiplier = 60 * 60 * 24 * 7;
    } else if (hasType("d")) {
        multiplier = 60 * 60 * 24;
    } else if (hasType("h")) {
        multiplier = 60 * 60;
    } else if (hasType("min")) {
        multiplier = 60;
    } else if (hasType("s")) {
        multiplier = 1;
    } else {
        hasMatch = false;
        multiplier = 1;
    }

    if (end == tstring::npos) {
        end = matcher.pattern.length();
    }

    time_t ret = Util::toInt64(matcher.pattern.substr(0, end)) * multiplier;
    return make_pair(ret > 0 ? GET_TIME() - ret : ret, hasMatch);
}
Ejemplo n.º 29
0
void UploadQueueItemInfo::update()
{
	setText(COLUMN_FILE, Text::toT(Util::getFileName(getQi()->getFile())));
	setText(COLUMN_PATH, Text::toT(Util::getFilePath(getQi()->getFile())));
	setText(COLUMN_NICK, getQi()->getUser()->getLastNickT()); // [1] https://www.box.net/shared/plriwg50qendcr3kbjp5
	setText(COLUMN_HUB, WinUtil::getHubNames(getQi()->getHintedUser()).first); // [!] IRainman fix: hintedUser
	setText(COLUMN_TRANSFERRED, Util::formatBytesW(getQi()->getPos()) + _T(" (") + Util::toStringW((double)getQi()->getPos() * 100.0 / (double)getQi()->getSize()) + _T("%)"));
	setText(COLUMN_SIZE, Util::formatBytesW(getQi()->getSize()));
	setText(COLUMN_ADDED, Text::toT(Util::formatDigitalClock(getQi()->getTime())));
	setText(COLUMN_WAITING, Util::formatSecondsW(GET_TIME() - getQi()->getTime()));
	setText(COLUMN_SHARE, Util::formatBytesW(getQi()->getUser()->getBytesShared())); //[+]PPA
	setText(COLUMN_SLOTS, Util::toStringW(getQi()->getUser()->getSlots())); //[+]PPA
	// !SMT!-IP
	if (!m_location.isSet() && !m_ip.empty()) // [!] IRainman opt: Prevent multiple repeated requests to the database if the location has not been found!
	{
		m_location = Util::getIpCountry(m_ip);
		setText(COLUMN_IP, Text::toT(m_ip));
	}
	if (m_location.isKnown())
	{
		setText(COLUMN_LOCATION, m_location.getDescription());
	}
#ifdef PPA_INCLUDE_DNS
	// [!] IRainman opt.
	if (m_dns.empty())
	{
		m_dns = Socket::nslookup(m_ip);
		setText(COLUMN_DNS, Text::toT(m_dns)); // todo: paint later if not resolved yet
	}
	// [~] IRainman opt.
#endif
}
Ejemplo n.º 30
0
/*
 * Reclaim all small blocks waiting to be reclaimed.
 * Abort and return FALSE when/if (*stop_func)() returns TRUE.
 * If this returns TRUE, then it's safe to restart the world
 * with incorrectly cleared mark bits.
 * If ignore_old is TRUE, then reclaim only blocks that have been
 * recently reclaimed, and discard the rest.
 * Stop_func may be 0.
 */
GC_INNER GC_bool GC_reclaim_all(GC_stop_func stop_func, GC_bool ignore_old)
{
    word sz;
    unsigned kind;
    hdr * hhdr;
    struct hblk * hbp;
    struct obj_kind * ok;
    struct hblk ** rlp;
    struct hblk ** rlh;
#   ifndef SMALL_CONFIG
    CLOCK_TYPE start_time = 0; /* initialized to prevent warning. */
    CLOCK_TYPE done_time;

    if (GC_print_stats == VERBOSE)
        GET_TIME(start_time);
#   endif

    for (kind = 0; kind < GC_n_kinds; kind++) {
        ok = &(GC_obj_kinds[kind]);
        rlp = ok -> ok_reclaim_list;
        if (rlp == 0) continue;
        for (sz = 1; sz <= MAXOBJGRANULES; sz++) {
            rlh = rlp + sz;
            while ((hbp = *rlh) != 0) {
                if (stop_func != (GC_stop_func)0 && (*stop_func)()) {
                    return(FALSE);
                }
                hhdr = HDR(hbp);
                *rlh = hhdr -> hb_next;
                if (!ignore_old || hhdr -> hb_last_reclaimed == GC_gc_no - 1) {
                    /* It's likely we'll need it this time, too */
                    /* It's been touched recently, so this      */
                    /* shouldn't trigger paging.                */
                    GC_reclaim_small_nonempty_block(hbp, FALSE);
                }
            }
        }
    }
#   ifndef SMALL_CONFIG
    if (GC_print_stats == VERBOSE) {
        GET_TIME(done_time);
        GC_log_printf("Disposing of reclaim lists took %lu msecs\n",
                      MS_TIME_DIFF(done_time,start_time));
    }
#   endif
    return(TRUE);
}