Beispiel #1
0
int 
main(int argc, char *argv[])
{
    float timeStep = 0.1f;
    uint32_t nIntegrations = 1000;
    uint32_t num_particles_x = 16;
    uint32_t num_particles_y = 16;
    uint32_t num_particles = num_particles_x * num_particles_y;
    uint32_t num_levels = logf(num_particles) / logf(4.f);
    uint32_t num_coefficients = 4;
    uint32_t memory_size = 256 * 1024 * 1024;
    initialize_data(memory_size, num_particles_x, num_particles_y,
            num_levels, num_coefficients);

    for(uint32_t loop = 0; loop < nIntegrations; loop++) {
        calculate_multipoles();
        reset_forces();
        calculate_forces();
        integrate(timeStep);
    }

    const char filename[] = "out.txt";
    debug_write_positions_to_file(filename);

    return 0;
}
Beispiel #2
0
/*
 * Function: insert_data
 *
 * Description: This routine inserts the data into the table
 *
 */
void insert_data()
{

  colp *colsptr;
  sword colindex;

  row_count = 0;
  while (row_count < numrows)
  {

    colsptr = cols;
    numinsert = numrows - row_count < MAX_ROWS_PER_INSERT ?
                       numrows - row_count : MAX_ROWS_PER_INSERT;

    for (colindex = 0; colindex < NUMCOLS; colsptr++, colindex++)
    {
       initialize_data(colsptr->c_buf, colsptr->c_size, colsptr->c_rlen,
                       numinsert);
       colsptr->c_curlen = numinsert;
    }

                      /* using offset zero - we want all the rows right away */
    if (oexec(&cda))
    {
        err_report(&cda);
        do_exit(OCI_EXIT_FAILURE);
    }

    printf(" Number of rows processed so far is %d\n", retval);

    row_count += numinsert;
  }

}
BOOL wing_editor::Create()
{
	BOOL r;
	int i;
	CComboBox *box;

	r = CDialog::Create(IDD, Fred_main_wnd);
	box = (CComboBox *) GetDlgItem(IDC_ARRIVAL_LOCATION);
	box->ResetContent();
	for (i=0; i<MAX_ARRIVAL_NAMES; i++)
		box->AddString(Arrival_location_names[i]);

	box = (CComboBox *) GetDlgItem(IDC_DEPARTURE_LOCATION);
	box->ResetContent();
	for (i=0; i<MAX_DEPARTURE_NAMES; i++)
		box->AddString(Departure_location_names[i]);

	m_hotkey = 0;
	m_waves_spin.SetRange(1, 99);
	m_arrival_tree.link_modified(&modified);  // provide way to indicate trees are modified in dialog
	m_arrival_tree.setup((CEdit *) GetDlgItem(IDC_HELP_BOX));
	m_departure_tree.link_modified(&modified);
	m_departure_tree.setup();
	m_arrival_delay_spin.SetRange(0, 999);
	m_departure_delay_spin.SetRange(0, 999);

	initialize_data(1);
	return r;
}
Beispiel #4
0
static void dispatch_rts (
    pami_context_t       context,      /**< IN: PAMI context */
    void               * cookie,       /**< IN: dispatch cookie */
    const void         * header_addr,  /**< IN: header address */
    size_t               header_size,  /**< IN: header size */
    const void         * pipe_addr,    /**< IN: address of PAMI pipe buffer */
    size_t               pipe_size,    /**< IN: size of PAMI pipe buffer */
    pami_endpoint_t origin,
pami_recv_t        * recv)        /**< OUT: receive message structure */
{
  volatile size_t * active = (volatile size_t *) cookie;
  fprintf (stderr, ">> 'rts' dispatch function.  cookie = %p (active: %zu), header_size = %zu, pipe_size = %zu, recv = %p\n", cookie, *active, header_size, pipe_size, recv);

  rts_info_t * rts = (rts_info_t *) header_addr;
  fprintf (stderr, "   'rts' dispatch function.  rts->origin = 0x%08x, rts->bytes = %zu\n", rts->origin, rts->bytes);

  /*assert(pipe_addr!=NULL); */
  /*pami_memregion_t * origin_memregion = (pami_memregion_t *) pipe_addr; */

  get_info_t * get = (get_info_t *) malloc (sizeof(get_info_t));
  get->value  = active;
  get->origin = rts->origin;
  get->bytes  = rts->bytes;
  get->pad    = 16;

  initialize_data (get->buffer, 0, 6);
  print_data (get->buffer, 12*4);

  /* Create a memregion for the data buffer. */
  size_t bytes = 0;
  pami_result_t pami_rc = PAMI_Memregion_create (context, get->buffer, 12*4, &bytes, &(get->memregion));
  if (PAMI_SUCCESS != pami_rc) {
      fprintf (stderr, "PAMI_Memregion_create failed with rc = %d\n", pami_rc) ;
      exit(1);
  }

  /* Perform the rdma get operation */
  pami_rget_simple_t parameters;
  parameters.rma.dest    = rts->origin;
  parameters.rma.bytes   = rts->bytes;
  parameters.rma.cookie  = get;
  parameters.rma.done_fn = get_done;
  parameters.rdma.local.mr      = &(get->memregion);
  parameters.rdma.local.offset  = 16; 
  parameters.rdma.remote.mr     = &(rts->memregion);
  parameters.rdma.remote.offset = 0;

  fprintf (stderr, "   'rts' dispatch function.  Before PAMI_Rget()\n");
  pami_result_t status = PAMI_Rget (context, &parameters);
  fprintf (stderr, "   'rts' dispatch function.   After PAMI_Rget(), status = %d\n", status);
  if (status != PAMI_SUCCESS)
    get_done (context, (void *) get, status);

  fprintf (stderr, "<< 'rts' dispatch function.\n");

  return;
}
Beispiel #5
0
static void
fr_application_startup (GApplication *application)
{
	G_APPLICATION_CLASS (fr_application_parent_class)->startup (application);

	fr_application_register_archive_manager_service (FR_APPLICATION (application));
	initialize_data ();
	initialize_app_menu (application);
}
Beispiel #6
0
static DFBResult
wm_join( CoreDFB *core, void *wm_data, void *shared_data )
{
     WMData    *data   = wm_data;
     WMShared  *shared = shared_data;

     D_DEBUG_AT( WM_Unique, "wm_join()\n" );

     initialize_data( core, data, shared );

     return unique_wm_module_init( core, data, shared, false );
}
Beispiel #7
0
// Initialize the methodDataOop corresponding to a given method.
void methodDataOopDesc::initialize(methodHandle method) {
  ResourceMark rm;

  // Set the method back-pointer.
  _method = method();
  set_creation_mileage(mileage_of(method()));

  // Initialize flags and trap history.
  _nof_decompiles = 0;
  _nof_overflow_recompiles = 0;
  _nof_overflow_traps = 0;
  assert(sizeof(_trap_hist) % sizeof(HeapWord) == 0, "align");
  Copy::zero_to_words((HeapWord*) &_trap_hist,
                      sizeof(_trap_hist) / sizeof(HeapWord));

  // Go through the bytecodes and allocate and initialize the
  // corresponding data cells.
  int data_size = 0;
  int empty_bc_count = 0;  // number of bytecodes lacking data
  BytecodeStream stream(method);
  Bytecodes::Code c;
  while ((c = stream.next()) >= 0) {
    int size_in_bytes = initialize_data(&stream, data_size);
    data_size += size_in_bytes;
    if (size_in_bytes == 0)  empty_bc_count += 1;
  }
  _data_size = data_size;
  int object_size = in_bytes(data_offset()) + data_size;

  // Add some extra DataLayout cells (at least one) to track stray traps.
  int extra_data_count = compute_extra_data_count(data_size, empty_bc_count);
  int extra_size = extra_data_count * DataLayout::compute_size_in_bytes(0);

  // Add a cell to record information about modified arguments.
  // Set up _args_modified array after traps cells so that
  // the code for traps cells works.
  DataLayout *dp = data_layout_at(data_size + extra_size);

  int arg_size = method->size_of_parameters();
  dp->initialize(DataLayout::arg_info_data_tag, 0, arg_size+1);

  object_size += extra_size + DataLayout::compute_size_in_bytes(arg_size+1);

  // Set an initial hint. Don't use set_hint_di() because
  // first_di() may be out of bounds if data_size is 0.
  // In that situation, _hint_di is never used, but at
  // least well-defined.
  _hint_di = first_di();

  post_initialize(&stream);

  set_object_is_parsable(object_size);
}
Beispiel #8
0
void MethodData::initialize() {
  No_Safepoint_Verifier no_safepoint;  // init function atomic wrt GC
  ResourceMark rm;

  init();
  set_creation_mileage(mileage_of(method()));

  // Go through the bytecodes and allocate and initialize the
  // corresponding data cells.
  int data_size = 0;
  int empty_bc_count = 0;  // number of bytecodes lacking data
  _data[0] = 0;  // apparently not set below.
  BytecodeStream stream(method());
  Bytecodes::Code c;
  while ((c = stream.next()) >= 0) {
    int size_in_bytes = initialize_data(&stream, data_size);
    data_size += size_in_bytes;

    if (is_empty_data(size_in_bytes, c)) empty_bc_count++;
  }
  _data_size = data_size;
  int object_size = in_bytes(data_offset()) + data_size;

  // Add some extra DataLayout cells (at least one) to track stray traps.
  int extra_data_count = compute_extra_data_count(data_size, empty_bc_count);
  int extra_size = extra_data_count * DataLayout::compute_size_in_bytes(0);
  object_size += extra_size;

  Copy::zero_to_bytes((HeapWord*) extra_data_base(), extra_size);

#ifndef GRAALVM
  // Add a cell to record information about modified arguments.
  // Set up _args_modified array after traps cells so that
  // the code for traps cells works.
  DataLayout *dp = data_layout_at(data_size + extra_size);

  int arg_size = method()->size_of_parameters();
  dp->initialize(DataLayout::arg_info_data_tag, 0, arg_size+1);

  object_size += DataLayout::compute_size_in_bytes(arg_size+1);
#endif

  // Set an initial hint. Don't use set_hint_di() because
  // first_di() may be out of bounds if data_size is 0.
  // In that situation, _hint_di is never used, but at
  // least well-defined.
  _hint_di = first_di();

  post_initialize(&stream);

  set_size(object_size);
}
Beispiel #9
0
/* This function can be called from within the sigprof handler and therefore
 * must be signal safe.  no strdup and friends.
 */
static void send_samples (TLS* tls)
{
    Assert(tls != NULL);

    tls->header.time_end = CBTF_GetTime();
    tls->header.addr_begin = tls->buffer.addr_begin;
    tls->header.addr_end = tls->buffer.addr_end;

    /* rank is not filled until mpi_init finished. safe to set here*/
    tls->header.rank = monitor_mpi_comm_rank();

    tls->data.pc.pc_len = tls->buffer.length;
    tls->data.count.count_len = tls->buffer.length;
    tls->data.events.events_len = tls->buffer.length;

#if 0
int bufsize = tls->buffer.length * sizeof(tls->buffer);
int pcsize =  tls->buffer.length * sizeof(tls->data.pc.pc_val);
int countsize =  tls->buffer.length * sizeof(tls->data.count.count_val);

fprintf(stderr,"[%d:%d] HWCSAMP SEND SAMPLES\n", tls->header.pid,tls->header.omp_tid);
fprintf(stderr,"send_samples: size of tls data is %d, buffer is %d\n",sizeof(tls->data), sizeof(tls->buffer));
fprintf(stderr,"send_samples: size of tls PC data is %d  %d, COUNT is %d  %d\n",tls->buffer.length , pcsize,tls->buffer.length , countsize);
fprintf(stderr,"send_samples: size of tls HASH is %d\n", sizeof(tls->buffer.hash_table));
fprintf(stderr,"send_samples: size of tls data pc buff is %d\n", sizeof(tls->data.pc.pc_val)*CBTF_HWCPCBufferSize);
fprintf(stderr,"send_samples: size of tls data count buff is %d\n", sizeof(tls->data.count.count_val)*CBTF_HWCPCBufferSize);
fprintf(stderr,"send_samples: size of tls hwccounts is %d\n", sizeof(tls->buffer.hwccounts));
fprintf(stderr,"send_samples: size of CBTF_evcounts is %d\n", sizeof(CBTF_evcounts)*CBTF_HWCPCBufferSize);
fprintf(stderr,"send_samples: size of lon long is %d\n", sizeof(long long));
fprintf(stderr,"send_samples: size of uint64_t is %d\n", sizeof(uint64_t));
fprintf(stderr,"send_samples: size of CBTF_HWCPCData is %d\n", sizeof(CBTF_HWCPCData));
int eventssize =  tls->buffer.length * sizeof(tls->data.events.events_val);
fprintf(stderr,"send_samples: size of eventssize = %d\n",eventssize);
#endif

#ifndef NDEBUG
    if (IsCollectorDebugEnabled) {
	    fprintf(stderr, "[%ld,%d] hwcsamp send_samples:\n",tls->header.pid, tls->header.omp_tid);
	    fprintf(stderr, "[%ld,%d] time_range(%lu,%lu) addr range[%#lx, %#lx] pc_len(%d) count_len(%d)\n",
		tls->header.pid, tls->header.omp_tid,
		tls->header.time_begin,tls->header.time_end,
		tls->header.addr_begin,tls->header.addr_end,
		tls->data.pc.pc_len,
		tls->data.count.count_len);
	}
#endif

    cbtf_collector_send(&(tls->header), (xdrproc_t)xdr_CBTF_hwcsamp_data, &(tls->data));

    /* Re-initialize the data blob's header */
    initialize_data(tls);
}
Beispiel #10
0
static DFBResult
wm_initialize( CoreDFB *core, void *wm_data, void *shared_data )
{
     WMData    *data   = wm_data;
     WMShared  *shared = shared_data;

     D_DEBUG_AT( WM_Unique, "wm_initialize()\n" );

     initialize_data( core, data, shared );

     D_MAGIC_SET( shared, WMShared );

     return unique_wm_module_init( core, data, shared, true );
}
Beispiel #11
0
void main(int argc, char **argv) {
	
	struct timeval start_t, end_t;
	struct timezone tzdummy;

	complex A[512*512], B[512*512], C[512*512];
	
	/* Initialize Data*/
	initialize_data(f1_name, A);
	initialize_data(f2_name, B);
	
	gettimeofday(&start_t, &tzdummy);
	
	/* 2D FFT on A */
	execute_fft(A, 1);
	transpose(A);
	execute_fft(A, 1);
	
	
	/* 2D FFT on B */
	execute_fft(B, 1);
	transpose(B);
	execute_fft(B, 1);
	
	/* Multiplication Step */
	execute_mm(A, B, C);
	
	/* 2D FFT on C */
	execute_fft(C, -1);
	transpose(C);
	execute_fft(C, -1);
	
	gettimeofday(&end_t, &tzdummy);
	output_data(f_out, C);
	printf("\nElapsed time = %g s\n", (double)((unsigned int)end_t.tv_usec - (unsigned int)start_t.tv_usec) / 1000000.0);
	printf("--------------------------------------------\n");
}
Beispiel #12
0
int
main (int   argc,
      char *argv[])
{
	GnomeProgram *program;
	char         *description;

	if (! g_thread_supported ()) {
		g_thread_init (NULL);
		gdk_threads_init ();
	}

	bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

	description = g_strdup_printf ("- %s", _("View and organize your images"));
	context = g_option_context_new (description);
	g_free (description);
	g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);

	program = gnome_program_init ("gthumb", VERSION,
				      LIBGNOMEUI_MODULE,
				      argc, argv,
				      GNOME_PARAM_GOPTION_CONTEXT, context,
				      GNOME_PARAM_HUMAN_READABLE_NAME, _("gThumb"),
				      GNOME_PARAM_APP_PREFIX, GTHUMB_PREFIX,
				      GNOME_PARAM_APP_SYSCONFDIR, GTHUMB_SYSCONFDIR,
				      GNOME_PARAM_APP_DATADIR, GTHUMB_DATADIR,
				      GNOME_PARAM_APP_LIBDIR, GTHUMB_LIBDIR,
				      NULL);

	gnome_vfs_init ();				      
	gnome_authentication_manager_init ();
	glade_gnome_init ();
	gthumb_init ();
	initialize_data ();
	prepare_app ();

	gdk_threads_enter ();
	gtk_main ();
	gdk_threads_leave ();

	release_data ();
	return 0;
}
static void
on_bus_acquired (GDBusConnection *connection,
		 const char      *name,
		 gpointer         user_data)
{
	guint registration_id;

	registration_id = g_dbus_connection_register_object (connection,
							     FR_SERVICE_PATH,
							     introspection_data->interfaces[0],
							     &interface_vtable,
							     NULL,
							     NULL,  /* user_data_free_func */
							     NULL); /* GError** */
	g_assert (registration_id > 0);

	initialize_data ();
}
Beispiel #14
0
int main (int argc, char* argv[]) {

    struct timespec start, end;
    
    initOpenCL();

    /* START Measurements */
    get_date(argc, argv);
    clock_gettime(CLOCK_MONOTONIC, &start);

    int arraySize = SIZE;
    size_t bufferSize = arraySize * sizeof(double);
    double* inputA = (double*) malloc (bufferSize);
    double* inputB = (double*) malloc (bufferSize);
    double* output = (double*) malloc (bufferSize);


    /* Initilise data */
    initialize_data(arraySize, inputA, inputB);

    /* Computation */
    vector_sum(arraySize, inputA, inputB, output);

    /* END Measurements */
    clock_gettime(CLOCK_MONOTONIC, &end);
    get_date(argc, argv);

    /* Check results */
    //check_results(arraySize, inputA, inputB, output);

    /* Cleaning */
    cleanUpOpenCL();

    double res=0;
    int i;
    for (i = 0; i < arraySize; i++) {
      res = res + output[i] ;
    }

    times = (((double)(end.tv_sec  - start.tv_sec)*1000) +
             ((double)(end.tv_nsec - start.tv_nsec)/1000000));
    //cout << "Time to finish: " << times << " ms" << endl;
    printf("Time to finish %6.0f ms [check = %e]\n", times, res);
}
Beispiel #15
0
gcp_solution_t* antcol(gcp_t *problem) {/*{{{*/

	int c = 0;
	gcp_solution_t *result;
	result = malloc(sizeof(gcp_solution_t));

	initialize_data(problem);
	best_ant->ncolors = INT_MAX;

	int terminate = FALSE;

	while (!terminate) {

		initialize_var_phero(problem);
		construct_solutions(problem, c);
		local_search(problem);
		update_pheromone_trails(problem);

		c++;

		if (problem->flags & FLAG_VERBOSE) {
			printf("Cycle %d - Colors used: %d\n", c, best_ant->ncolors);
		}
		else {
			printf("*");
			fflush(stdout);
		}

		/* test stop conditions */
		if ((problem->flags & FLAG_CYCLE) && problem->ncycles <= c)
			terminate = TRUE;
		if ((problem->flags & FLAG_TIME) && problem->time <= current_usertime_secs())
			terminate = TRUE;


	}

	*result = *best_ant;
	result->ncycles = c;

	return result;

}/*}}}*/
Beispiel #16
0
static void dispatch_rts (
    pami_context_t       context,      /**< IN: PAMI context */
    void               * cookie,       /**< IN: dispatch cookie */
    const void         * header_addr,  /**< IN: header address */
    size_t               header_size,  /**< IN: header size */
    const void         * pipe_addr,    /**< IN: address of PAMI pipe buffer */
    size_t               pipe_size,    /**< IN: size of PAMI pipe buffer */
    pami_endpoint_t origin,
pami_recv_t        * recv)        /**< OUT: receive message structure */
{
  volatile size_t * active = (volatile size_t *) cookie;
  fprintf (stderr, ">> 'rts' dispatch function.  cookie = %p (active: %zu), header_size = %zu, pipe_size = %zu, recv = %p\n", cookie, *active, header_size, pipe_size, recv);

  rts_info_t * rts = (rts_info_t *) header_addr;
  fprintf (stderr, "   'rts' dispatch function.  rts->origin = 0x%08x, rts->bytes = %zu, rts->source = %p\n", rts->origin, rts->bytes, rts->source);

  size_t pad  = BUFFERSIZE;
  get_info_t * get = (get_info_t *) malloc (sizeof(get_info_t));
  get->value  = active;
  get->origin = rts->origin;
  get->bytes  = rts->bytes;
  get->pad    = pad;

  initialize_data (get->buffer, 0, 6);
  print_data (get->buffer, 12*4);

  pami_get_simple_t parameters;
  parameters.rma.dest    = rts->origin;
  parameters.rma.hints   = null_send_hint; 
  parameters.rma.bytes   = rts->bytes;
  parameters.rma.cookie  = get;
  parameters.rma.done_fn = get_done;
  parameters.addr.local  = (void *) (get->buffer+4);
  parameters.addr.remote = rts->source;
  PAMI_Get (context, &parameters);

  fprintf (stderr, "<< 'rts' dispatch function.\n");

  return;
}
Beispiel #17
0
/**
 * Send events.
 *
 * Sends all the events in the tracing buffer to the framework for storage in 
 * the experiment's database. Then resets the tracing buffer to the empty state.
 * This is done regardless of whether or not the buffer is actually full.
 */
static void send_samples(TLS *tls)
{
    Assert(tls != NULL);

    tls->header.id = strdup(cbtf_collector_unique_id);
    tls->header.time_end = CBTF_GetTime();
    tls->header.rank = monitor_mpi_comm_rank();

#ifndef NDEBUG
	if (IsCollectorDebugEnabled) {
	    fprintf(stderr, "[%ld,%d] mpi send_samples:\n",tls->header.pid, tls->header.omp_tid);
	    fprintf(stderr, "[%ld,%d] time_range(%lu,%lu) addr range[%lx, %lx] stacktraces_len(%u) events_len(%u)\n",
		tls->header.pid, tls->header.omp_tid,
		tls->header.time_begin,tls->header.time_end,
		tls->header.addr_begin,tls->header.addr_end,
#if defined(PROFILE)
		tls->data.stacktraces.stacktraces_len
#else
		tls->data.stacktraces.stacktraces_len,
		tls->data.events.events_len
#endif
	    );
	}
#endif

#if defined(PROFILE)
    cbtf_collector_send(&(tls->header), (xdrproc_t)xdr_CBTF_mpi_profile_data, &(tls->data));
#else
#if defined(EXTENDEDTRACE)
    cbtf_collector_send(&(tls->header), (xdrproc_t)xdr_CBTF_mpi_exttrace_data, &(tls->data));
#else
    cbtf_collector_send(&(tls->header), (xdrproc_t)xdr_CBTF_mpi_trace_data, &(tls->data));
#endif
#endif

    /* Re-initialize the data blob's header */
    initialize_data(tls);
}
void MainWindow::on_actionOpen_triggered() {
    filename = QFileDialog::getOpenFileName(this, "Open Stadium ROM", QString(), "Pokémon Stadium ROM (*.z64)");

    // ROM opening
    if(!filename.isEmpty()){
        QFile romfile(filename);
        romfile.open(QIODevice::ReadOnly);

        QDataStream read(&romfile);

        // ***** Checks the ROM validity *****
        if(romfile.size() == 0x2000000) {
            romfile.seek(0x00);
            read>>header_PI_settings;
            romfile.seek(0x04);
            read>>header_clockrate;
            romfile.seek(0x08);
            read>>header_boot_address;
            romfile.seek(0x0C);
            read>>header_release;
            romfile.seek(0x10);
            read>>header_crc1;
            romfile.seek(0x14);
            read>>header_crc2;
            romfile.seek(0x18);
            read>>header_reserved1;
            romfile.seek(0x1C);
            read>>header_reserved2;
            romfile.seek(0x20);
            read>>header_name1;
            romfile.seek(0x24);
            read>>header_name2;
            romfile.seek(0x28);
            read>>header_name3;
            romfile.seek(0x2C);
            read>>header_name4;
            romfile.seek(0x30);
            read>>header_name5;
            romfile.seek(0x34);
            read>>header_reserved3;
            romfile.seek(0x38);
            read>>header_rom_format;
            romfile.seek(0x3C);
            read>>header_game_id;
            romfile.seek(0x3E);
            read>>header_region_code;
            romfile.seek(0x3F);
            read>>header_rom_version;

            // Checks ROM language and validity
            rom_check();
            romfile.seek(0);

            if(this->romtype != INVALID){
                // ***** Reads the ROM data *****
                // Initialization
                initialize_char_table();
                initialize_data();
                initialize_min_levels();
                initialize_iv_statexp_groups();

                // Formulas
                read_ch_formula(romfile);
                read_damage_variance(romfile);
                read_highCH_shift(romfile);
                read_burn_shift(romfile);
                read_odds_paralysis(romfile);

                // Pokémon names
                read_pkm_names(romfile);
                initialize_nicknames();

                // Pokémon data
                read_pkm_data(romfile);
                read_pokedex_data(romfile);

                // Moves names and data
                read_move_names(romfile);
                read_move_data(romfile);
                read_move_descriptions(romfile);
                read_tmhm_data(romfile);

                // Types names
                read_type_names(romfile);

                // Types chart (Weaknesses and Resistances)
                read_type_chart(romfile);

                // Experience data
                read_experience_data(romfile);

                // CPU Trainers / Rentals data
                read_cpu_rentals(romfile);
                initialize_trainers_names();
            }
        }
Beispiel #19
0
void main(int argc, char **argv) {
	
	double start_t;
	double end_t;
	
	int my_rank, p, my_loc_rank, loc_p;
	complex *A;
	complex *B;
	complex *C;

	/* initialize MPI */
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &p);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	
	/* Create MPI Datatype for Complex */
    const float nitems=2;
    int          blocklengths[2] = {1,1};
    MPI_Datatype types[2] = {MPI_FLOAT, MPI_FLOAT};
    MPI_Aint     offsets[2];

    offsets[0] = offsetof(complex, r);
    offsets[1] = offsetof(complex, i);

    MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_complex);
    MPI_Type_commit(&mpi_complex);
	
	int workload = 512 / p;
	complex a[512*workload];
	complex b[512*workload];
	complex c[512*workload];
	
	
	/* Split the first two groups and a collector group*/
	if(my_rank == 0) {
		MPI_Comm_split(MPI_COMM_WORLD, 0, my_rank, &comm1);
		MPI_Comm_split(MPI_COMM_WORLD, MPI_UNDEFINED, my_rank, &comm2);
		MPI_Comm_split(MPI_COMM_WORLD, 0, my_rank, &commR2);
	} else if(my_rank < p/2) {
		MPI_Comm_split(MPI_COMM_WORLD, 0, my_rank, &comm1);
		MPI_Comm_split(MPI_COMM_WORLD, MPI_UNDEFINED, my_rank, &comm2);
		MPI_Comm_split(MPI_COMM_WORLD, MPI_UNDEFINED, my_rank, &commR2);
	} else {
		MPI_Comm_split(MPI_COMM_WORLD, MPI_UNDEFINED, my_rank-(p/2), &comm1);
		MPI_Comm_split(MPI_COMM_WORLD, 0, my_rank-(p/2), &comm2);	
		MPI_Comm_split(MPI_COMM_WORLD, 0, my_rank-(p/2), &commR2);
	}
	
	/* Split the group for the latter two tasks */
	/* All processors may participate, we only need one group for the two tasks */
	MPI_Comm_split(MPI_COMM_WORLD, 0, my_rank, &comm3);
	
	
	/* Initialize Data*/
	workload = 512 / (p/2);
	if(my_rank == 0) {
		A = malloc(512*512 * sizeof(complex));
		B = malloc(512*512 * sizeof(complex));
		C = malloc(512*512 * sizeof(complex));
		initialize_data(f1_name, A);
		start_t = MPI_Wtime();
	} else if(my_rank == p/2 || p == 1) {
		B = malloc(512*512 * sizeof(complex));
		initialize_data(f2_name, B);
	}
	
	if(my_rank < p/2) {
		MPI_Scatter(A, 512*workload, mpi_complex, 
		            a, 512*workload, mpi_complex,
		            0, comm1);
	} else {
		MPI_Scatter(B, 512*workload, mpi_complex, 
		            b, 512*workload, mpi_complex,
		            0, comm2);
	}
	
	/* 2D FFT on A */
	if(my_rank < p/2) {
	
		MPI_Comm_rank(comm1, &my_loc_rank);
		MPI_Comm_size(comm1, &loc_p);
		
		execute_fft(a, 1, loc_p, my_loc_rank);
		MPI_Gather(a, 512*workload, mpi_complex,
			       A, 512*workload, mpi_complex,
			       0, comm1);
		if(my_loc_rank == 0) {
			transpose(A);
		}
		MPI_Scatter(A, 512*workload, mpi_complex, 
				    a, 512*workload, mpi_complex,
				    0, comm1);
		execute_fft(a, 1, loc_p, my_loc_rank);
		
	} else if(my_rank >= p/2 || p == 1) {
	
		/* 2D FFT on B */
		MPI_Comm_rank(comm2, &my_loc_rank);
		MPI_Comm_size(comm2, &loc_p);
		execute_fft(b, 1, loc_p, my_loc_rank);
		MPI_Gather(b, 512*workload, mpi_complex,
		  	       B, 512*workload, mpi_complex,
			       0, comm2);
		if(my_loc_rank == 0) {
			transpose(B);
		}
		MPI_Scatter(B, 512*workload, mpi_complex, 
			        b, 512*workload, mpi_complex,
			        0, comm2);
		execute_fft(b, 1, loc_p, my_loc_rank);
	}
	
	/* Multiplication Step */
	workload = 512 / p;
	sync_tasks(a, b, A, B, p, my_rank);
	MPI_Scatter(A, 512*workload, mpi_complex, 
			        b, 512*workload, mpi_complex,
			        0, comm3);
	MPI_Scatter(B, 512*workload, mpi_complex, 
			        b, 512*workload, mpi_complex,
			        0, comm3);
	execute_mm(a, b, c, p, my_rank);
	
	/* 2D FFT on C */
	execute_fft(c, -1, p, my_rank);
	MPI_Gather(c, 512*workload, mpi_complex,
			   C, 512*workload, mpi_complex,
			   0, comm3);
	if(my_rank == 0) {
		transpose(C);
	}
	MPI_Scatter(C, 512*workload, mpi_complex, 
			   c, 512*workload, mpi_complex,
			   0, comm3);
	execute_fft(c, -1, p, my_rank);
	MPI_Gather(c, 512*workload, mpi_complex,
			   C, 512*workload, mpi_complex,
			   0, comm3);
	
	
	end_t = MPI_Wtime();
	
	if(my_rank == 0) {
		output_data(f_out, C);
		printf("\nElapsed time = %g s\n", end_t - start_t);
		printf("--------------------------------------------\n");
		int i;
		for(i = 0; i < 512*512; i++) {
			free(&A[i]);
			free(&B[i]);
			free(&C[i]);
		}
	}
	
	MPI_Finalize();
}
Beispiel #20
0
/*-------------------------------------------------------------------*/
void fer_sim(int *rate)
{
    int     i,j,k,ix;
    short   fer_flag;

    static short    first_time = 1;


    if( first_time )
    {
        first_time = 0;

        /*...initialize data...*/
        initialize_data();

        /*...set seed...*/
        if (fer_sim_seed == 0) {
            fer_sim_seed = (int)(time(NULL) & 0x0fff);
        }

        if ((trans_fp=fopen(trans_fname,"r")) == NULL)
        {
            fprintf(stderr,"ERROR:  Cannot open file \"%s\" for reading.\n",trans_fname );
            fprintf(log_fp,"ERROR:  Cannot open file \"%s\" for reading.\n",trans_fname );
            exit(1);
        }
        else
        {
            fprintf(log_fp,"FER Transition Prob. File              : \"%s\"\n\n",trans_fname);
        }
	
        /* record initial parameters in log file */
        fprintf(log_fp,"Random number generator initial seed : %d\n",fer_sim_seed);

        /* read transition probability matrices */
        for(i=0;i<NSTATES;i++)
        {
            for(j=0;j<NRATES_IN;j++)
            {
                for(k=0;k<NRATES_OUT;k++)
                {
                    ix = fscanf(trans_fp,"%lf",&p[i][j][k]);
                    if(ix!=1)
                    {
                        printf("Error in read of transition matrices file\n");
                        fprintf(log_fp,"Error in read of transition matrices file\n");
                        exit(1);
                    }
                }
            }
        }
	
        /* convert probability transition matrices to cumulative values */
        if(!prob_to_cum())
        {
            fprintf(stderr,"Problem with prob_to_cum()\n");
            fprintf(log_fp,"Problem with prob_to_cum()\n");
        }

	
        /* clear rate and transition stat matrices */
        initialize_stats();

    } /* end if( first_time ) */
	


    /* read encoded data */
    /* convert code to internal value */
    if(*rate==fullRate) rate_in = FULL;
    else if(*rate==halfRate) rate_in = HALF;
    else if(*rate==quarRate) rate_in = QUARTER;
    else if(*rate==eighRate) rate_in = EIGHTH;
    else if(*rate==fullProb) rate_in = FULL_ERRS;
    else rate_in = -1;   /* other codes invalid */

    fer_flag = 0;

    if (rate_in == -1)
    {
        fer_flag = 1;
    }
    else if (rate_in == -2)
    {
        fer_flag = 1;
        fprintf(stderr,"Encoded data file format error -- invalid rate specified in %d-th frame\n",frame_cnt);
        fprintf(log_fp,"Encoded data file format error -- invalid rate specified in %d-th frame\n",frame_cnt);
    }

		
    trans(rate_in);  /* determine rate_out, event from random number and  */
		                 /* transition probability matrix */

    /* Force RANDOM and MODIFIED to be an ERASURE (for simplicity) */
    if(event==RANDOM)           /* random data for the given frame length */
    {
        event = ERASURE;
    }
    else if(event==MODIFIED)    /* XOR data with a randomly selected mask */
    {
        event = ERASURE;
    }
    else if( fer_flag == 1 )
    {
        event = ERASURE;
    }

		
    /* determine output rate code */
    if(event==ERASURE) rate_code = erasRate;
    else if(rate_out==FULL) rate_code = fullRate;
    else if(rate_out==HALF) rate_code = halfRate;
    else if(rate_out==QUARTER) rate_code = quarRate;
    else if(rate_out==EIGHTH) rate_code = eighRate;
    else if(rate_out==FULL_ERRS) rate_code = fullProb;

    *rate = rate_code;

}
Beispiel #21
0
/*Algoritmo Principal*/
int main(int argc, char *argv[])
{
    char name[20];// = "_kita_1";
    char archiveName[20] = "archive";
	char fitputName[20] = "fitput";
	char varputName[20] = "varput";
	char hvName[20]= "hv";
	unsigned int i, j, t;
	unsigned int fun, gen;
	clock_t  startTime, endTime;
	double duration, clocktime;
	FILE *fitfile,*varfile;
/*Parametros iniciales*/

    strcpy(name,argv[1]);
    fun = atoi(argv[2]);
    gen = atoi(argv[3]);

    printf("%s %d %d \n",name,fun,gen);

    initialize_data(fun,gen);
/*Iniciar variables*/
	initialize_memory();

	/*
	sprintf(name,"kita_1_");
	sprintf(archiveName,strcat(name,"archive.out"));
	sprintf(fitputName, strcat(name,"fitput.out"));
	sprintf(varputName, strcat(name,"varput.out"));
	sprintf(hvName,strcat(name,"hv.out"));
*/
	//fitfile = fopen(strcat(strcat(fitputName,name),".out"),"w");
	//varfile = fopen(strcat(strcat(varputName,name),".out"),"w");
	//hv = fopen(strcat(strcat(hvName,name),".out"),"w");
/* Iniciar generador de aleatorios*/
	initialize_rand();
	startTime = clock();
/* Iniciar contador de generaciones*/
	t = 0;
/* Iniciar valores de la poblacion de manera aleatoria*/
	initialize_pop();
/* Calcular velocidad inicial*/
	initialize_vel();
/* Evaluar las particulas de la poblacion*/
	evaluate();
/* Almacenar el pBest inicial (variables and valor de aptitud) de las particulas*/
	store_pbests();
/* Insertar las particulas no domindas de la poblacion en el archivo*/

	insert_nondom();
	//printf("\n%d",nondomCtr);
/*Ciclo Principal*/
	while(t <= maxgen)
	{
		//clocktime = (clock() - startTime)/(double)CLOCKS_PER_SEC;
		/*if(verbose > 0 && t%printevery==0 || t == maxgen)
		{
			fprintf(stdout,"Generation %d Time: %.2f sec\n",t,clocktime);
			fflush(stdout);
		}*/
		/*if(t%printevery==0 || t == maxgen)
		{
			fprintf(outfile,"Generation %d Time: %.2f sec\n",t,clocktime);
		}*/
    /* Calcular la nueva velocidad de cada particula en la pooblacion*/
		//printf("\n 1");
		compute_velocity();

    /* Calcular la nueva posicion de cada particula en la poblacion*/
        //printf("\n 2");
        compute_position();
    /* Mantener las particulas en la poblacion de la poblacion en el espacio de busqueda*/
		//printf("\n 3");
		maintain_particles();
    /* Pertubar las particulas en la poblacion*/
		if(t < maxgen * pMut)
			mutate(t);

    /* Evaluar las particulas en la poblacion*/
		//printf("\n 4");
		evaluate();
    /* Insertar nuevas particulas no domindas en el archivo*/
		//printf("\n 5");
		update_archive();
    /* Actualizar el pBest de las particulas en la poblacion*/
		//printf("\n 6");
		update_pbests();
    /* Escribir resultados del mejor hasta ahora*/
    //verbose > 0 && t%printevery==0 || t == maxgen
		/*if(t%printevery==0 || t == maxgen)
		{
			//fprintf(outfile, "Size of Pareto Set: %d\n", nondomCtr);
			fprintf(fitfile, "%d\n",t);
			fprintf(varfile, "%d\n",t);
			for(i = 0; i < nondomCtr; i++)
			{
			    for(j = 0; j < maxfun; j++)
                    fprintf(fitfile, "%f ", archiveFit[i][j]);
                fprintf(fitfile, "\n");
			}
			fprintf(fitfile, "\n\n");
			fflush(fitfile);
			for(i = 0; i < nondomCtr; i++)
			{
			    for(j = 0; j < maxfun; j++)
                    fprintf(varfile, "%f ", archiveVar[i][j]);
                fprintf(varfile, "\n");
			}
			fprintf(varfile, "\n\n");
			fflush(varfile);
		}*/
    /* Incrementar contador de generaciones*/
        t++;
        //printf("%d\n",t);
	}
 /* Escribir resultados en el archivo */
	save_results(strcat(strcat(archiveName,name),".out"));
	endTime = clock();
	duration = ( endTime - startTime ) / (double)CLOCKS_PER_SEC;
	fprintf(stdout, "%lf sec\n", duration);
	//fclose(fitfile);
	//fclose(varfile);
	free_memory();
	return EXIT_SUCCESS;
}
Beispiel #22
0
int main (int argc, char ** argv)
{
  volatile size_t _rts_active = 1;
  volatile size_t _ack_active = 1;

  memset(&null_send_hint, 0, sizeof(null_send_hint));

  pami_client_t client;
  pami_context_t context[2];

  char                  cl_string[] = "TEST";
  pami_result_t result = PAMI_ERROR;

  result = PAMI_Client_create (cl_string, &client, NULL, 0);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable to create pami client. result = %d\n", result);
    return 1;
  }

#ifdef TEST_CROSSTALK
  size_t num = 2;
#else
  size_t num = 1;
#endif
  result = PAMI_Context_createv(client, NULL, 0, context, num);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable to create pami context(s). result = %d\n", result);
    return 1;
  }

  pami_configuration_t configuration;

  configuration.name = PAMI_CLIENT_TASK_ID;
  result = PAMI_Client_query(client, &configuration,1);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable query configuration (%d). result = %d\n", configuration.name, result);
    return 1;
  }
  pami_task_t task_id = configuration.value.intval;
  fprintf (stderr, "My task id = %d\n", task_id);

  configuration.name = PAMI_CLIENT_NUM_TASKS;
  result = PAMI_Client_query(client, &configuration,1);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable query configuration (%d). result = %d\n", configuration.name, result);
    return 1;
  }
  size_t num_tasks = configuration.value.intval;
  fprintf (stderr, "Number of tasks = %zu\n", num_tasks);
  if (num_tasks < 2)
  {
    fprintf (stderr, "Error. This test requires at least 2 tasks. Number of tasks in this job: %zu\n", num_tasks);
    return 1;
  }

  pami_dispatch_hint_t options={};

#ifdef USE_SHMEM_OPTION
  options.use_shmem = PAMI_HINT_ENABLE;
  fprintf (stderr, "##########################################\n");
  fprintf (stderr, "shared memory optimizations forced ON\n");
  fprintf (stderr, "##########################################\n");
#elif defined(NO_SHMEM_OPTION)
  options.use_shmem = PAMI_HINT_DISABLE;
  fprintf (stderr, "##########################################\n");
  fprintf (stderr, "shared memory optimizations forced OFF\n");
  fprintf (stderr, "##########################################\n");
#endif

  size_t i = 0;
#ifdef TEST_CROSSTALK
  for (i=0; i<2; i++)
#endif
  {
    pami_dispatch_callback_function fn;

    fprintf (stderr, "Before PAMI_Dispatch_set(%d) .. &_rts_active = %p, _rts_active = %zu\n", DISPATCH_ID_RTS, &_rts_active, _rts_active);
    fn.p2p = dispatch_rts;
    result = PAMI_Dispatch_set (context[i],
                                DISPATCH_ID_RTS,
                                fn,
                                (void *)&_rts_active,
                                options);
    if (result != PAMI_SUCCESS)
    {
      fprintf (stderr, "Error. Unable register pami dispatch. result = %d\n", result);
      return 1;
    }

    fprintf (stderr, "Before PAMI_Dispatch_set(%d) .. &_ack_active = %p, _ack_active = %zu\n", DISPATCH_ID_ACK, &_ack_active, _ack_active);
    fn.p2p = dispatch_ack;
    result = PAMI_Dispatch_set (context[i],
                                DISPATCH_ID_ACK,
                                fn,
                                (void *)&_ack_active,
                                options);
    if (result != PAMI_SUCCESS)
    {
      fprintf (stderr, "Error. Unable register pami dispatch. result = %d\n", result);
      return 1;
    }
  }

  if (task_id == 0)
  {
    pami_send_immediate_t parameters;
#ifdef TEST_CROSSTALK
    fprintf (stdout, "PAMI_Rget('simple') functional test [crosstalk]\n");
    fprintf (stdout, "\n");
    PAMI_Endpoint_create (client, num_tasks-1, 1, &parameters.dest);
#else
    fprintf (stdout, "PAMI_Rget('simple') functional test\n");
    fprintf (stdout, "\n");
    PAMI_Endpoint_create (client, num_tasks-1, 0, &parameters.dest);
#endif


    /* Allocate some memory from the heap. */
    void * send_buffer = malloc (BUFFERSIZE);

    /* Initialize the memory for validation. */
    initialize_data ((uint32_t *)send_buffer, BUFFERSIZE, 0);
    print_data (send_buffer, BUFFERSIZE);

    /* Send an 'rts' message to the target task and provide the memory region */
    rts_info_t rts_info;
    PAMI_Endpoint_create (client, 0, 0, &rts_info.origin);
    rts_info.bytes  = BUFFERSIZE;

    /* Create a memory region for this memoru buffer */
    size_t bytes = 0;
    pami_result_t pami_rc = PAMI_Memregion_create (context[0], send_buffer, BUFFERSIZE, &bytes, &(rts_info.memregion));

    if (PAMI_SUCCESS != pami_rc) {
      fprintf (stderr, "PAMI_Memregion_create failed with rc = %d\n", pami_rc) ;
      exit(1);
    }

    parameters.dispatch        = DISPATCH_ID_RTS;
    parameters.header.iov_base = &rts_info;
    parameters.header.iov_len  = sizeof(rts_info_t);
    parameters.data.iov_base   = NULL;
    parameters.data.iov_len    = 0;
fprintf (stderr, "Before PAMI_Send_immediate()\n");
    PAMI_Send_immediate (context[0], &parameters);

    /* wait for the 'ack' */
fprintf (stderr, "Wait for 'ack', _ack_active = %zu\n", _ack_active);
    while (_ack_active != 0)
    {
      result = PAMI_Context_advance (context[0], 100);
      if (result != PAMI_SUCCESS && result != PAMI_EAGAIN)
      {
        fprintf (stderr, "Error. Unable to advance pami context. result = %d\n", result);
        return 1;
      }
    }

    /* Destroy the local memory region */
    PAMI_Memregion_destroy (context[0], &(rts_info.memregion));

    free (send_buffer);

    switch (_ack_status)
    {
      case 0:
        fprintf (stdout, "Test PASSED\n");
        break;
      case 1:
        fprintf (stdout, "Test FAILED (rget error)\n");
        break;
      case 2:
        fprintf (stdout, "Test FAILED (data error)\n");
        break;
      default:
        fprintf (stdout, "Test FAILED (unknown error)\n");
        break;
    }

  }
  else if (task_id == num_tasks-1)
  {
#ifdef TEST_CROSSTALK
      size_t contextid = 1;
#else
      size_t contextid = 0;
#endif

    /* wait for the 'rts' */
fprintf (stderr, "Wait for 'rts', _rts_active = %zu, contextid = %zu\n", _rts_active, contextid);
    while (_rts_active != 0)
    {
      result = PAMI_Context_advance (context[contextid], 100);
      if (result != PAMI_SUCCESS && result != PAMI_EAGAIN)
      {
        fprintf (stderr, "Error. Unable to advance pami context. result = %d\n", result);
        return 1;
      }
    }
  }
fprintf (stderr, "Test completed .. cleanup\n");

 result = PAMI_Context_destroyv (context, num);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable to destroy pami context. result = %d\n", result);
    return 1;
  }

  result = PAMI_Client_destroy(&client);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable to destroy pami client. result = %d\n", result);
    return 1;
  }

  /*fprintf (stdout, "Success (%d)\n", task_id); */

  return 0;
};
Beispiel #23
0
int main(int argc, char *argv[]) {/*{{{*/


	extern char *optarg;
	char op, *namefilein;
	int it;

	ALPHA = 2;
	BETA = 1;
	RHO = 0.4;
	M = 40;
	it = 1000;


	/* Usando getopt para tratamento dos argumentos */
	struct option longopts[] = {/*{{{*/
		{"alpha", 1, NULL, 'a'},	
		{"beta", 1, NULL, 'b'},	
		{"rho", 1, NULL, 'r'},	
		{"ants", 1, NULL, 'm'},
		{"iterations", 1, NULL, 'i'},
		{"help", 0, NULL, 'h'},
	};/*}}}*/


	while ((op = getopt_long(argc, argv, "a:b:r:m:i:h", longopts, NULL)) != -1) {/*{{{*/
		switch (op) {
			case 'a':
				ALPHA = atoi(optarg);
				break;
			case 'b':
				BETA = atoi(optarg);
				break;
			case 'r':
				RHO = atoi(optarg);
				break;
			case 'm':
				M = atoi(optarg);
				break;
			case 'i':
				it = atoi(optarg);
				break;
			case 'h':
				print_help(argv[0]);
				return 0;
//			case ':':
//				/* a opção anterior precisa de especificação mas não recebeu */
//				printf("Erro: arquivo de saida nao especificado. Use '-h' para ajuda.\n");
//				return 0;
//			case '?':
//				/* opção não existe */
//				printf("Erro: opcao '-%c' nao existente. Use '-h' para ajuda.\n", optopt);
//				return 0;
		}
	}/*}}}*/


/*{{{*/
	/* O único argumento não capturado acima é o nome do arquivo de entrada,
	 * se existir */
	if (optind < argc) {
		namefilein = malloc(sizeof(char) * strlen(argv[optind]));
		strcpy(namefilein, argv[optind++]);

		/* verificar se foi passado algum argumento a mais */
		if (optind < argc) {
			printf("Erro: foram passados muitos argumentos. Use '-h' para ajuda.\n");
			return 0;
		}
	}
	else {
		printf("Erro: falta nome do arquivo de entrada. Use '-h' para ajuda.\n");
		return 0;
	}


	if (!fopen(namefilein, "r")) {
		printf("Erro: arquivo ou diretorio inexistente.\n");
		return 0;
	}
/*}}}*/


	int terminate = 0;
	int k = 0;

	initialize_data(namefilein);

	while (!terminate && k != it) {
		construct_solutions();
		local_search();
		//update_statistics();
		update_pheromone_trails();
		k++;
	}


	int menor = 0;
	for (k = 1; k < M; k++) {
		if (ant[menor].tour_length > ant[k].tour_length) {
			menor = k;
		}
	}
	printf("%d: %d\n", menor, ant[menor].tour_length);

	return 0;
}/*}}}*/
Beispiel #24
0
Datei: rcd.c Projekt: joeshaw/rcd
int
main (int argc, const char **argv)
{
    GMainLoop *main_loop;
    struct sigaction sig_action;
    const char *config_file;
    char *python_path;

    g_thread_init (NULL);
    g_type_init ();

    rcd_executable_name = g_strdup (argv[0]);

    rcd_options_parse (argc, argv);

    if (rcd_options_get_show_version ()) {
        g_print ("%s\n", rcd_about_name ());
        g_print ("%s\n\n", rcd_about_copyright ());
        exit (0);
    }

    config_file = rcd_options_get_config_file ();
    if (config_file && !g_file_test (config_file, G_FILE_TEST_EXISTS)) {
        g_printerr ("Unable to find config file '%s'\n", config_file);
        g_printerr ("rcd aborting\n");

        exit (-1);
    }

    root_check ();
    if (!rcd_options_get_late_background ())
        daemonize ();

    /* Set up SIGTERM and SIGQUIT handlers */
    sig_action.sa_handler = signal_handler;
    sigemptyset (&sig_action.sa_mask);
    sig_action.sa_flags = 0;
    sigaction (SIGINT,  &sig_action, NULL);
    sigaction (SIGTERM, &sig_action, NULL);
    sigaction (SIGQUIT, &sig_action, NULL);

    /* Set up SIGHUP handler. */
    sig_action.sa_handler = sighup_handler;
    sigemptyset (&sig_action.sa_mask);
    sig_action.sa_flags = 0;
    sigaction (SIGHUP, &sig_action, NULL);
    
    /* If it looks like rcd-buddy is in the right place, set up
       handlers for crashes */
    python_path = g_find_program_in_path ("python");
    if (python_path != NULL
        && g_file_test (SHAREDIR "/rcd-buddy", G_FILE_TEST_EXISTS)) {
        sig_action.sa_handler = crash_handler;
        sigaction (SIGSEGV, &sig_action, NULL);
        sigaction (SIGFPE,  &sig_action, NULL);
        sigaction (SIGBUS,  &sig_action, NULL);
        sigaction (SIGABRT, &sig_action, NULL);
    }
    g_free (python_path);

    rcd_privileges_init ();

    initialize_logging ();

    /* Check to see if the password file is secure.
       If it isn't, a big warning will go out to the log file. */
    rcd_identity_password_file_is_secure ();

    /* Set the GPG keyring for package verification */
    rc_verification_set_keyring (SHAREDIR "/rcd.gpg");

    /* Create mid and secret */
    if (!g_file_test (SYSCONFDIR "/mcookie", G_FILE_TEST_EXISTS))
        rcd_create_uuid (SYSCONFDIR "/mcookie");

    if (!g_file_test (SYSCONFDIR "/partnernet", G_FILE_TEST_EXISTS))
        rcd_create_uuid (SYSCONFDIR "/partnernet");

    /* Add memory usage watcher */
    rcd_heartbeat_register_func (heartbeat_memory_monitor, NULL);

    initialize_rc_packman ();
    initialize_rc_services ();
    initialize_rc_world ();
    initialize_rpc ();

    if (!rcd_options_get_no_modules_flag ())
        rcd_module_init ();

    /* We can't daemonize any later than this, so hopefully module
       initialization won't be slow. */
    if (rcd_options_get_late_background ()) {
        
        rc_debug (RC_DEBUG_LEVEL_ALWAYS, "Running daemon in background.");
        daemonize ();

        /* We need to reinit logging, since the file descriptor gets closed
           when we daemonize. */
        rcd_log_reinit ();

        /* Say hello again, so it gets stored in the log file. */
        hello ();
    }

    rcd_rpc_local_server_start ();

    if (rcd_prefs_get_remote_server_enabled ()) {
        if (!rcd_rpc_remote_server_start ())
            exit (-1);
    }

    initialize_data ();
    
    /* No heartbeat if we have initialized from a dump file. */
    if (rcd_options_get_dump_file () == NULL)
        rcd_heartbeat_start ();

    main_loop = g_main_loop_new (NULL, TRUE);
    g_main_loop_run (main_loop);

    /*
     * We'll never reach here, because we'll exit() out in
     * rcd-shutdown.c.
     */
    g_assert_not_reached ();

    return 0;
} /* main */
Beispiel #25
0
void main(int argc, char **argv) {
	
	double start_t, end_t;
	
	int my_rank, p;
	complex A[512*512], B[512*512], C[512*512];

	/* initialize MPI */
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &p);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	
	/* Create MPI Datatype for Complex */
    const float nitems=2;
    int          blocklengths[2] = {1,1};
    MPI_Datatype types[2] = {MPI_FLOAT, MPI_FLOAT};
    MPI_Aint     offsets[2];

    offsets[0] = offsetof(complex, r);
    offsets[1] = offsetof(complex, i);

    MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_complex);
    MPI_Type_commit(&mpi_complex);
	
	/* Initialize Data*/
	if(my_rank == 0) {
		initialize_data(f1_name, A);
		initialize_data(f2_name, B);
		start_t = MPI_Wtime();
		dist_data(A, p);
		dist_data(B, p);
	} else {
		recv_data(A, p, my_rank);
		recv_data(B, p, my_rank);
	}
	
	/* 2D FFT on A */
	execute_fft(A, 1, p, my_rank);
	collect_data(A, p, my_rank);
	if(my_rank == 0) {
		transpose(A);
		dist_data(A, p);
	} else {
		recv_data(A, p, my_rank);
	}
	execute_fft(A, 1, p, my_rank);
	
	/* 2D FFT on B */
	execute_fft(B, 1, p, my_rank);
	collect_data(B, p, my_rank);
	if(my_rank == 0) {
		transpose(B);
		dist_data(B, p);
	} else {
		recv_data(B, p, my_rank);
	}
	execute_fft(B, 1, p, my_rank);
	
	/* Multiplication Step */
	execute_mm(A, B, C, p, my_rank);
	
	/* 2D FFT on C */
	execute_fft(C, -1, p, my_rank);
	collect_data(C, p, my_rank);
	if(my_rank == 0) {
		transpose(C);
		dist_data(C, p);
	} else {
		recv_data(C, p, my_rank);
	}
	execute_fft(C, -1, p, my_rank);
	collect_data(C, p, my_rank);
	
	end_t = MPI_Wtime();
	
	if(my_rank == 0) {
		output_data(f_out, C);
		printf("\nElapsed time = %g s\n", end_t - start_t);
		printf("--------------------------------------------\n");
	}
	
	MPI_Finalize();
}
Beispiel #26
0
int main (int argc, char *argv[])
   {
   Zoltan_DD_Directory *dd;
   ZTIMER *zt;

   int        myproc;         /* MPI rank, my processor's MPI ID      */
   int        nproc;          /* MPI size, number of processors       */
   ZOLTAN_ID_PTR  glist = NULL;   /* list of GIDs                     */
   ZOLTAN_ID_PTR  llist = NULL;   /* list of LIDs                     */
   ZOLTAN_ID_PTR  ulist = NULL;   /* list of user data of type 
                                      ZOLTAN_ID_TYPE                   */
   int       *plist = NULL;    /* list of partitions                   */
   int       *olist = NULL;    /* list of owners                       */
   Param      param ;          /* program's adjustable parameters      */
   char      *store = NULL;    /* non directory storage of test data   */
   Data      *data  = NULL;    /* pointer into store                   */

   /* these are all temporary variables */
   int   new_owner;
   int   count;
   int   i;
   char *p;
   int   err;
   int   errcount;
   int   loop;
   char str[100];      /* for building output messages */
   static int timer[7] = {-1,-1,-1,-1,-1,-1,-1};
   char *yo = "DD_Main";


   /* initialize MPI communications, ignore errors */
   MPI_Init (&argc, &argv);
   MPI_Comm_rank (MPI_COMM_WORLD, &myproc);
   MPI_Comm_size (MPI_COMM_WORLD, &nproc);

   get_params (&param);     /* read input parameters */

   zt = Zoltan_Timer_Create(1);
   MACRO_TIMER_START(5, "Total time", 0);

   MACRO_TIMER_START(0, "DD_Create time", 0);
   err = Zoltan_DD_Create (&dd, MPI_COMM_WORLD, param.glen, param.llen,
    param.ulen, param.tlen, param.debug_level);
   if (err != ZOLTAN_OK)
      ZOLTAN_PRINT_ERROR (myproc, yo, "Failed return from DD Create");
   MACRO_TIMER_STOP(0);

   param.slen = sizeof (Data) + sizeof(ZOLTAN_ID_TYPE)
              * (param.glen + param.llen + param.ulen);
   param.slen = Zoltan_Align(param.slen);
   store = (char*) ZOLTAN_MALLOC (param.count * param.slen);

   /* allocate storage for various lists */
   glist = (ZOLTAN_ID_PTR) ZOLTAN_MALLOC(sizeof(ZOLTAN_ID_TYPE) * param.count
         * param.glen);
   plist = (int*) ZOLTAN_MALLOC (sizeof(int) * param.count);
   olist = (int*) ZOLTAN_MALLOC (sizeof(int) * param.count);
   if (param.llen)
      llist = (ZOLTAN_ID_PTR) ZOLTAN_MALLOC (sizeof (ZOLTAN_ID_TYPE)
            * param.count * param.llen);
   if (param.ulen)
      ulist = (ZOLTAN_ID_PTR) ZOLTAN_MALLOC (sizeof (ZOLTAN_ID_TYPE)
            * param.count * param.ulen) ;


   if (store == NULL || glist == NULL || (param.llen != 0 && llist == NULL)
    || (param.ulen != 0 && ulist == NULL) || plist == NULL || olist == NULL)  {
       ZOLTAN_PRINT_ERROR (myproc, yo, "Unable to malloc storage lists");
       return ZOLTAN_MEMERR;
   }

   initialize_data (&param, store, nproc);

   /* create & update directory with myproc's initial simulated GIDs */
   count = 0;
   for (p = store; p < store + param.count * param.slen; p += param.slen)
      if (((Data *)p)->new_owner == myproc) {
         ZOLTAN_SET_ID (param.glen, glist + count * param.glen, ((Data*)p)->id);
         if (param.llen)
            ZOLTAN_SET_ID (param.llen, llist + count * param.llen, 
             ((Data *)p)->id + param.glen);
         if (param.ulen)
            ZOLTAN_SET_ID (param.ulen, ulist + count * param.ulen, 
             ((Data *)p)->id + (param.glen + param.llen));
         plist [count] = ((Data *)p)->partition;
         ++count;
      }
   MACRO_TIMER_START (1, "DD_Update timer", 0);
   err = Zoltan_DD_Update (dd, glist, llist, ulist, plist, count);
   if (err != ZOLTAN_OK)
      ZOLTAN_PRINT_ERROR (myproc, yo, "Failed return from DD Update");
   MACRO_TIMER_STOP(1);

   i = 0;
   for (p = store; p < store + param.count * param.slen; p += param.slen)  {
      ZOLTAN_SET_ID (param.glen, glist + i * param.glen, ((Data *)p)->id);
      ++i;
   }
   MACRO_TIMER_START(2, "DD_Find timer", 0);
   err = Zoltan_DD_Find (dd, glist, llist, ulist, plist, param.count, olist);
   if (err != ZOLTAN_OK)
      ZOLTAN_PRINT_ERROR (myproc, yo, "Failed return from DD Find");
   MACRO_TIMER_STOP(2);

   errcount = 0;
   for (i = 0; i < param.count; i++)
       if (olist[i] != ((Data *) (store + i * param.slen))->new_owner)
          ++errcount;
   if (errcount)
      sprintf (str, "FIRST TEST FAILED, errcount is %d", errcount);
   else
      sprintf (str, "FIRST TEST SUCCESSFUL");
   ZOLTAN_PRINT_INFO (myproc, yo, str);

   /* repeatedly simulate moving "dots" around the system */
   for (loop = 0; loop < param.nloops; loop++)
       {
       for (p = store; p < store + param.count * param.slen; p += param.slen)
          ((Data*) p)->old_owner = ((Data*) p)->new_owner;

       /* randomly exchange some dots and randomly reassign others */
       for (i = 0; i < (param.pmove * param.count)/100; i++)  {
          Data *d1, *d2;
          d1 = (Data*) (store + param.slen * (rand() % param.count));
          d2 = (Data*) (store + param.slen * (rand() % param.count));
          new_owner     = d1->new_owner;
          d1->new_owner = d2->new_owner;
          d2->new_owner = new_owner;
       }

       for (i = 0; i < (param.count * param.pscatter)/100; i++)
          ((Data*) (store + param.slen *(rand() % param.count)))->new_owner
           = rand() % nproc;

       /* determine which new GIDs myproc gained, and update directory */
       count = 0;
       for (p = store; p < store + param.count * param.slen; p += param.slen)
           if (((Data*)p)->new_owner == myproc)  {
              ((Data*)p)->id[param.glen] = count;  /* set LID */
              ZOLTAN_SET_ID (param.glen, glist + count * param.glen, 
               ((Data *)p)->id);
              if (param.llen)
                 ZOLTAN_SET_ID (param.llen, llist + count * param.llen, 
                  ((Data*)p)->id + param.glen);
              if (param.ulen)
                  ZOLTAN_SET_ID (param.ulen, ulist + count * param.ulen, 
                   ((Data*)p)->id + (param.glen + param.llen));
              plist [count] = ((Data *)p)->partition;
              ++count;
           }
       MACRO_TIMER_START(1, "DD_Update", 0);
       err = Zoltan_DD_Update (dd, glist, llist, ulist, plist, count);
       if (err != ZOLTAN_OK)
          ZOLTAN_PRINT_ERROR (myproc, yo, "Failed return from DD Update");
       MACRO_TIMER_STOP(1);

       /* use directory to "find" GIDs  */
       i = 0;
       for (p = store; p < store + param.count * param.slen; p += param.slen) {
          ZOLTAN_SET_ID (param.glen, glist + i * param.glen, ((Data *)p)->id);
          ++i;
       }
 
       MACRO_TIMER_START(2, "DD_Find timer", 0);
       if (loop % 5 == 0)
          err = Zoltan_DD_Find(dd,glist,NULL,ulist,plist,param.count,olist);
       else if (loop % 7 == 0)
          err = Zoltan_DD_Find(dd,glist,llist,NULL,plist,param.count,olist);
       else if (loop % 9 == 0)
          err = Zoltan_DD_Find(dd,glist,llist,ulist,NULL,param.count,olist);
       else if (loop % 2 == 0) 
          err = Zoltan_DD_Find(dd,glist,llist,ulist,plist,param.count,NULL);
       else
           err = Zoltan_DD_Find(dd,glist,llist,ulist,plist,param.count,olist);
       if (err != ZOLTAN_OK)
          ZOLTAN_PRINT_ERROR (myproc, yo, "Failed return from DD Find");
       MACRO_TIMER_STOP(2);

       if (loop % 2)  {
          errcount = 0 ;
          for (i = 0; i < param.count; i++)
             if (olist[i] != ((Data *)(store + i * param.slen))->new_owner)
                ++errcount;
          if (errcount)
             sprintf (str,"LOOP %d TEST FAILED, errcount is %d",loop,errcount);
          else
             sprintf (str, "LOOP %d TEST SUCCESSFUL", loop);
          ZOLTAN_PRINT_INFO (myproc, yo, str) ;
       }
       else  {
          sprintf (str, "LOOP %d Completed", loop);
          ZOLTAN_PRINT_INFO (myproc, yo, str);
       }

       /* randomly remove a percentage of GIDs from the directory */
       count = 0;
       for (i = 0; i < (param.count * param.pdelete)/100; i++)  {
          data = (Data*) (store + param.slen * (rand() % param.count));
          if (data->new_owner == myproc)  {
             ZOLTAN_SET_ID (param.glen, glist + count * param.glen, data->id);
             ++count;
          }
          data->new_owner = NO_PROC;
       }
       MACRO_TIMER_START(3, "DD_Remove timer", 0);
       err = Zoltan_DD_Remove (dd, glist, count);
       MACRO_TIMER_STOP(3);
       if (err != ZOLTAN_OK)
          ZOLTAN_PRINT_ERROR (myproc, yo, "Failed return from DD Remove");

       /* update directory (put directory entries back in) */
       for (p = store; p < store + param.count * param.slen; p += param.slen)
          if (((Data*)p)->new_owner == NO_PROC)
              ((Data*)p)->new_owner = loop % nproc; /* place in new location */

       count = 0;
       for (p = store; p < store + param.count * param.slen; p += param.slen)
          if (((Data*)p)->new_owner == myproc)  {
              ZOLTAN_SET_ID(param.glen,glist+count*param.glen,((Data*)p)->id);
              if (param.llen)
                 ZOLTAN_SET_ID (param.llen, llist + count * param.llen, 
                  ((Data*)p)->id + param.glen);
              if (param.ulen)
                  ZOLTAN_SET_ID(param.ulen, ulist + count * param.ulen, 
                   ((Data *)p)->id + (param.glen + param.llen));
              plist [count] = ((Data*)p)->partition;
              ++count;
           }
       MACRO_TIMER_START(1, "DD_Update timer", 0);
       err = Zoltan_DD_Update (dd, glist, NULL, NULL, NULL, count);
       if (err != ZOLTAN_OK)
          ZOLTAN_PRINT_ERROR (myproc, yo, "Failed return from DD Update");
       MACRO_TIMER_STOP(1);
   }

   /* now Find directory info for GIDs myproc now owns and validate */
   count = 0;
   for (i = 0; i < param.count; i++) {
      data = (Data *) (store + i * param.slen);
      if (data->new_owner == myproc)  {
         ZOLTAN_SET_ID (param.glen, glist + count * param.glen, data->id);
         ++count;
      }
   }
   MACRO_TIMER_START(2, "DD_Find", 0);
   err = Zoltan_DD_Find (dd, glist, NULL, NULL, NULL, count, olist);
   if (err != ZOLTAN_OK)
      ZOLTAN_PRINT_ERROR (myproc, yo, "Failed return from DD Find");
   MACRO_TIMER_STOP(2);

   errcount = 0;
   for (i = 0; i < count; i++)
       if (olist[i] != myproc)
          ++errcount;
   if (errcount)  {
      sprintf (str, "errcount is %d", errcount);
      ZOLTAN_PRINT_ERROR (myproc, yo, str);
   }
   else
      ZOLTAN_PRINT_INFO (myproc, yo, "TEST SUCCESSFUL");

   Zoltan_DD_Stats (dd);

   /* done, now free memory, stop MPI & directory, return */
   ZOLTAN_FREE (&store);
   ZOLTAN_FREE (&glist);
   ZOLTAN_FREE (&plist);
   ZOLTAN_FREE (&olist);

   if (param.llen) ZOLTAN_FREE (&llist);
   if (param.ulen) ZOLTAN_FREE (&ulist);

   ZOLTAN_PRINT_INFO (myproc, yo, "Completing program");
   MACRO_TIMER_START(4, "DD_Destroy", 0);
   Zoltan_DD_Destroy (&dd);
   MACRO_TIMER_STOP(4);
   MACRO_TIMER_STOP(5);

   Zoltan_Timer_PrintAll(zt, 0, MPI_COMM_WORLD, stderr);


   MPI_Finalize ();
   return ZOLTAN_OK;
   }
Beispiel #27
0
/**
 * Called by the CBTF collector service in order to start data collection.
 */
void cbtf_collector_start(const CBTF_DataHeader* const header)
{
/**
 * Start tracing.
 *
 * Starts MPI event tracing for the thread executing this function.
 * Initializes the appropriate thread-local data structures.
 *
 * @param arguments    Encoded function arguments.
 */
    /* Create and access our thread-local storage */
#ifdef USE_EXPLICIT_TLS
    TLS* tls = malloc(sizeof(TLS));
    Assert(tls != NULL);
    CBTF_SetTLS(TLSKey, tls);
    mpi_init_tls_done = true;
#else
    TLS* tls = &the_tls;
#endif
    Assert(tls != NULL);

    tls->defer_sampling=FALSE;

    /* Decode the passed function arguments */
    // Need to handle the arguments...
    CBTF_mpi_start_sampling_args args;
    memset(&args, 0, sizeof(args));
    
#if 0
    CBTF_DecodeParameters(arguments,
			  (xdrproc_t)xdr_CBTF_mpi_start_sampling_args,
			   &args);
#endif

#if defined(CBTF_SERVICE_USE_OFFLINE)

    /* If CBTF_MPI_TRACED is set to a valid list of mpi functions, trace only
     * those functions.
     * If CBTF_MPI_TRACED is set and is empty, trace all functions.
     * For any misspelled function name in CBTF_MPI_TRACED, silently ignore.
     * If all names in CBTF_MPI_TRACED are misspelled or not part of
     * TraceableFunctions, nothing will be traced.
     */
    const char* mpi_traced = getenv("CBTF_MPI_TRACED");

    if (mpi_traced != NULL && strcmp(mpi_traced,"") != 0) {
	strcpy(tls->CBTF_mpi_traced,mpi_traced);
    } else {
	strcpy(tls->CBTF_mpi_traced,all);
    }
#endif

    memcpy(&tls->header, header, sizeof(CBTF_DataHeader));

    /* Initialize the actual data blob */
    initialize_data(tls);

    /* We can not assign mpi rank in the header at this point as it may not
     * be set yet. assign an integer tid value.  omp_tid is used regardless of
     * whether the application is using openmp threads.
     * libmonitor uses the same numbering scheme as openmp.
     */
    tls->header.omp_tid = monitor_get_thread_num();

#ifndef NDEBUG
    IsCollectorDebugEnabled = (getenv("CBTF_DEBUG_COLLECTOR") != NULL);
    IsCollectorDetailDebugEnabled = (getenv("CBTF_DEBUG_COLLECTOR_DETAIL") != NULL);

    if (IsCollectorDebugEnabled) {
	fprintf(stderr,"[%ld,%d] ENTERED cbtf_collector_start.\n",tls->header.pid, tls->header.omp_tid);
    }
#endif

    /* Initialize the MPI function wrapper nesting depth */
    tls->nesting_depth = 0;
 
    /* Begin sampling */
    tls->header.time_begin = CBTF_GetTime();
    tls->do_trace = TRUE;
}
Beispiel #28
0
/**
 * Called by the CBTF collector service in order to start data collection.
 */
void cbtf_collector_start(const CBTF_DataHeader* header)
{
/**
 * Start sampling.
 *
 * Starts hardware counter (HWC) sampling for the thread executing this
 * function. Initializes the appropriate thread-local data structures and
 * then enables the sampling counter.
 *
 * @param arguments    Encoded function arguments.
 */
    /* Create and access our thread-local storage */
#ifdef USE_EXPLICIT_TLS
    TLS* tls = malloc(sizeof(TLS));
    Assert(tls != NULL);
    CBTF_SetTLS(TLSKey, tls);
#else
    TLS* tls = &the_tls;
#endif
    Assert(tls != NULL);


    tls->defer_sampling=false;

#ifndef NDEBUG
    IsCollectorDebugEnabled = (getenv("CBTF_DEBUG_COLLECTOR") != NULL);
    IsCollectorDetailsDebugEnabled = (getenv("CBTF_DEBUG_COLLECTOR_DETAILS") != NULL);
#if defined (HAVE_OMPT)
    IsOMPTDebugEnabled = (getenv("CBTF_DEBUG_COLLECTOR_OMPT") != NULL);
#endif
#endif

    /* Decode the passed function arguments */
    // Need to handle the arguments...
    CBTF_hwcsamp_start_sampling_args args;
    memset(&args, 0, sizeof(args));
    args.sampling_rate = 100;

    /* First set defaults */
    int hwcsamp_rate = 100;
    char* hwcsamp_papi_event = "PAPI_TOT_CYC,PAPI_TOT_INS";

#if defined (CBTF_SERVICE_USE_OFFLINE)
    char* hwcsamp_event_param = getenv("CBTF_HWCSAMP_EVENTS");
    if (hwcsamp_event_param != NULL) {
        hwcsamp_papi_event=hwcsamp_event_param;
    }

    const char* sampling_rate = getenv("CBTF_HWCSAMP_RATE");
    if (sampling_rate != NULL) {
        hwcsamp_rate=atoi(sampling_rate);
    }
    args.collector = 1;
    args.experiment = 0;
    tls->data.interval = (uint64_t)(1000000000) / (uint64_t)(hwcsamp_rate);;
#endif


    /* Initialize the actual data blob */
    memcpy(&tls->header, header, sizeof(CBTF_DataHeader));
    initialize_data(tls);


    /* We can not assign mpi rank in the header at this point as it may not
     * be set yet. assign an integer tid value.  omp_tid is used regardless of
     * whether the application is using openmp threads.
     * libmonitor uses the same numbering scheme as openmp.
     */
    tls->header.omp_tid = monitor_get_thread_num();
    tls->header.id = strdup(cbtf_collector_unique_id);
    tls->header.time_begin = CBTF_GetTime();


#ifndef NDEBUG
	if (IsCollectorDebugEnabled) {
	    fprintf(stderr,"[%ld,%d] ENTER cbtf_collector_start\n",tls->header.pid,tls->header.omp_tid);
	}
#endif
    if(hwcsamp_papi_init_done == 0) {
#ifndef NDEBUG
	if (IsCollectorDebugEnabled) {
	    fprintf(stderr,"[%ld,%d] cbtf_collector_start: initialize papi\n",tls->header.pid,tls->header.omp_tid);
	}
#endif
	CBTF_init_papi();
	tls->EventSet = PAPI_NULL;
	tls->data.clock_mhz = (float) hw_info->mhz;
	hwcsamp_papi_init_done = 1;
    } else {
	tls->data.clock_mhz = (float) hw_info->mhz;
    }


    /* PAPI SETUP */
    CBTF_Create_Eventset(&tls->EventSet);

    int rval = PAPI_OK;

#ifndef NDEBUG
    if (IsCollectorDebugEnabled) {
       fprintf(stderr, "PAPI Version: %d.%d.%d.%d\n", PAPI_VERSION_MAJOR( PAPI_VERSION ),
                        PAPI_VERSION_MINOR( PAPI_VERSION ),
                        PAPI_VERSION_REVISION( PAPI_VERSION ),
                        PAPI_VERSION_INCREMENT( PAPI_VERSION ) );
       fprintf(stderr,"System has %d hardware counters.\n", PAPI_num_counters());
    }
#endif

/* In Component PAPI, EventSets must be assigned a component index
 * before you can fiddle with their internals. 0 is always the cpu component */
#if (PAPI_VERSION_MAJOR(PAPI_VERSION)>=4)
    rval = PAPI_assign_eventset_component( tls->EventSet, 0 );
    if (rval != PAPI_OK) {
        CBTF_PAPIerror(rval,"CBTF_Create_Eventset assign_eventset_component");
        return;
    }
#endif

    /* NOTE: if multiplex is turned on, papi internaly uses a SIGPROF handler.
     * Since we are sampling potentially with SIGPROF or now SIGRTMIN and we
     * prefer to limit our events to 6, we do not need multiplexing.
     */
    if (getenv("CBTF_HWCSAMP_MULTIPLEX") != NULL) {
#if !defined(RUNTIME_PLATFORM_BGP) 
	rval = PAPI_set_multiplex( tls->EventSet );
	if ( rval == PAPI_ENOSUPP) {
	    fprintf(stderr,"CBTF_Create_Eventset: Multiplex not supported\n");
	} else if (rval != PAPI_OK)  {
	    CBTF_PAPIerror(rval,"CBTF_Create_Eventset set_multiplex");
	}
#endif
    }

    /* TODO: check return values of direct PAPI calls
     * and handle them as needed.
     */
    /* Rework the code here to call PAPI directly rather than
     * call any OPENSS helper functions due to inconsitent
     * behaviour seen on various lab systems
     */
    int eventcode = 0;
    rval = PAPI_OK;
    if (hwcsamp_papi_event != NULL) {
	char *tfptr, *saveptr=NULL, *tf_token;
	tfptr = strdup(hwcsamp_papi_event);
	for (tf_token = strtok_r(tfptr, ",", &saveptr);
	     tf_token != NULL;
	     tf_token = strtok_r(NULL, ",", &saveptr) ) {

	    PAPI_event_name_to_code(tf_token,&eventcode);
	    rval = PAPI_add_event(tls->EventSet,eventcode);

	    if (rval != PAPI_OK)  {
		CBTF_PAPIerror(rval,"CBTF_Create_Eventset PAPI_event_name_to_code");
	    }
	}

	if (tfptr) free(tfptr);
	
    } else {
	PAPI_event_name_to_code("PAPI_TOT_CYC",&eventcode);
	rval = PAPI_add_event(tls->EventSet,eventcode);
	PAPI_event_name_to_code("PAPI_TOT_INS",&eventcode);
	rval = PAPI_add_event(tls->EventSet,eventcode);
    }

#if defined (HAVE_OMPT)
    /* these are ompt specific.*/
    /* initialize the flags and counts for idle,wait_barrier.  */
    tls->thread_idle =  tls->thread_wait_barrier = tls->thread_barrier = false;
#endif

    /* Begin sampling */
    tls->header.time_begin = CBTF_GetTime();
    CBTF_Start(tls->EventSet);
    CBTF_Timer(tls->data.interval, hwcsampTimerHandler);
}
Beispiel #29
0
int main(void)
{
    int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes=1;
    char s[INET6_ADDRSTRLEN];
    int rv;

    // Initialize mutex
    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        return 1;
    }

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
                sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    if (p == NULL)  {
        fprintf(stderr, "server: failed to bind\n");
        return 2;
    }

    freeaddrinfo(servinfo); // all done with this structure

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }
    // Server ready
    // Initialize data
    initialize_data();

    printf("server: waiting for connections...\n");

    while(1) {  // main accept() loop
        sin_size = sizeof their_addr;
        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if (new_fd == -1) {
            perror("accept");
            continue;
        }

        inet_ntop(their_addr.ss_family,
            get_in_addr((struct sockaddr *)&their_addr),
            s, sizeof s);
        printf("server: got connection from %s\n", s);

        pthread_t thread;
        int rc = pthread_create(&thread, NULL,
                          handle_client, (void *)&new_fd);
    }

    pthread_mutex_destroy(&lock);

    return 0;
}