这篇教程C++ srand48函数代码示例写得很实用,希望能帮到您。
本文整理汇总了C++中srand48函数的典型用法代码示例。如果您正苦于以下问题:C++ srand48函数的具体用法?C++ srand48怎么用?C++ srand48使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。 在下文中一共展示了srand48函数的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。 示例1: mainint main(int argc, char *argv[]){ int n,i; REAL *y_ref, *y_ompacc, *x; REAL a = 123.456f; n = VEC_LEN; if (argc >= 2) n = atoi(argv[1]); y_ref = (REAL *) malloc(n * sizeof(REAL)); y_ompacc = (REAL *) malloc(n * sizeof(REAL)); x = (REAL *) malloc(n * sizeof(REAL)); srand48(1<<12); init(x, n); init(y_ref, n); memcpy(y_ompacc, y_ref, n*sizeof(REAL));#if 0//-------------------- begin of multi-gpu portion // Transformation point: obtain the number of devices to be used by default int GPU_N = xomp_get_num_devices(); printf("CUDA-capable device count: %i/n", GPU_N); // preparation for multiple GPUs // Transformation point: set first level thread count to be GPU count used omp_set_num_threads(GPU_N); #pragma omp parallel shared (GPU_N,x , y_ompacc, n) private(i) { int tid = omp_get_thread_num(); xomp_set_default_device (tid); long size, offset; XOMP_static_even_divide (0, n, GPU_N, tid, &offset, &size); printf("thread %d working on GPU devices %d with size %d copying data from y_ompacc with offset %d/n",tid, tid, size,offset); int j; #pragma omp target device (tid) map(tofrom: y_ompacc[offset:size]) map(to: x[offset:size],a,size, offset) #pragma omp parallel for shared(size, a) private(j) for (j = offset; j < offset+size; ++j) { y_ompacc[j] += a * x[j]; } }//-------------------- end of multi-gpu portion#else #pragma omp target device(*) map(tofrom: y_ompacc[0:n] dist_data(block)) map(to: x[0:n] dist_data(block),a,n) #pragma omp parallel for shared(x, y_ompacc, n, a) private(i) for (i = 0; i < n; ++i) y_ompacc[i] += a * x[i];#endif int num_threads; #pragma omp parallel shared (num_threads) { if (omp_get_thread_num() == 0) num_threads = omp_get_num_threads(); } // serial version axpy(x, y_ref, n, a); REAL checksum = check(y_ref, y_ompacc, n); printf("axpy(%d): checksum: %g/n", n, checksum); assert (checksum < 1.0e-10); free(y_ref); free(y_ompacc); free(x); return 0;}
开发者ID:InstRO,项目名称:InstRO-ROSE,代码行数:71,
示例2: main//reduce redistributes, updates 07/02/15 rncint main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; init_time_at(time,"# reading Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s /n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count(10); count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF/n"); for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d /n",i, count[i]);} //read the three input fits files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); if(Targ.size() == 0) { std::cerr << "ERROR: No targets found in " << F.Targfile << std::endl; myexit(1); } print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d /n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d /n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d /n",M.size()); F.Ngal=M.size(); F.Ntarg=Secret.size(); //establish priority classes init_time_at(time,"# establish priority clasess",t); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d priority %d number %d/n",i,M.priority_list[i],count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("computed neighbors/n"); std::cout.flush(); //P tiles in order specified by surveyFile Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %d plates from %s and %d fibers from %s/n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||//.........这里部分代码省略.........
开发者ID:apcooper,项目名称:fiberassign,代码行数:101,
示例3: mainint main(void){ // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; // keep playing until game over while (lives > 0 && bricks > 0) { // SCORE updateScoreboard(window,label,points); // BALL /* BOUNCING */ move(ball, x_velocity, y_velocity); pause(10); // MOUSE EVENT GEvent event = getNextEvent(MOUSE_EVENT); if (event != NULL) { /* if mouse was moved */ if (getEventType(event) == MOUSE_MOVED) { /*move paddle were mouse goes */ double x = getX(event) - getWidth(paddle) / 2; double y = 400; setLocation(paddle, x, y); } } /* Collision */ /* ball touching paddle */ GObject object = detectCollision(window, ball); if (object != NULL) { if (object == paddle) { y_velocity = -y_velocity; } else if (object != paddle) { if (strcmp(getType(object), "GRect") == 0) { removeGWindow(window,object); y_velocity = -y_velocity; points++; bricks--; } } } /* ball touching wall on the right */ if (getX(ball) + getWidth(ball) >= getWidth(window)) { x_velocity = -x_velocity; } /* ball touching wall on the left */ if (getX(ball) <= 0) { x_velocity = -x_velocity; } /* ball touching wall on the top */ if (getY(ball) <= 0) { y_velocity = -y_velocity; } /* ball touching wall on the bottom */ if (getY(ball) + getHeight(ball) >= getHeight(window)) { setLocation(ball,190,300); setLocation(paddle, 190, 400); lives--; waitForClick(); } } //.........这里部分代码省略.........
开发者ID:marialgutierrez,项目名称:CS50,代码行数:101,
示例4: random_rdwr_mpvoidrandom_rdwr_mp (int fd, long long blocks, int procs, int min_xfer_size, int max_xfer_size, int rdwr_iterations, int rwpercent, int do_log, int skip_block_zero){ static long long random_block; static long int charsread, charswrote; static long int rdwr_size; static long int elapsed_time; static long int start_time; static long int stop_time; static int p, j, count; static pid_t pid; static int i; static long int IOrate; static long long data_rate;#if DEBUG long min, max;#endif static char real_wrbuffer[MAX_TRANSFER_SIZE+512]; char *wrbuffer; static char *rbuffer = NULL; static int rdwr_rand; static int rdwr_type; /* Align the buffer */ wrbuffer = (char *)(((unsigned long long)real_wrbuffer+512) & ~0x1ff); if (rbuffer == NULL) { rbuffer = mmap(NULL, MAX_TRANSFER_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (rbuffer == NULL) err(1, "failed to get read buffer/n"); } for (i = 1; i <= (int) max_xfer_size; ++i) wrbuffer[i] = (char) i; rdwr_size = min_xfer_size; blocks = blocks - 1; /*Turn # of blocks into highest block # */ blocks = blocks - (MAX_TRANSFER_SIZE / 512); /*stay away from the end */#ifndef NO_BUFFER blocks = blocks - 3000;#endif#if DEBUG min = 10000; max = blocks - 10000;#endif#ifdef DEBUG printf ("blocks=%lld procs=%d min=%d max=%d iter=%d per=%d/n", blocks, procs, min_xfer_size, max_xfer_size, rdwr_iterations, rwpercent);#endif while (rdwr_size <= max_xfer_size) { start_time = MSTime (); pid = 1; /*i = 0; */ j = 0; for (p = 1; p <= procs; ++p) {/* Seed the random number generator. Adding "p" insures that *//* each seed is different, and that each child gets a different *//* sequence of random numbers. That way, two consecutive IO's *//* can't go to the same random block. */ srand48 ((unsigned int) time (NULL) + p);/* fork 'procs' number of child processes, each executing the benchmark code *//* if pid = 0, you're in a forked process, if pid > 0, you're in the parent */ pid = fork (); if (pid == 0) break; } switch (pid) { case -1: exit (EXIT_FAILURE); case 0: count = 0; while (count < rdwr_iterations) { random_block = (drand48 () * (blocks - 1) + skip_block_zero);#if DEBUG if (min > random_block) min = random_block; if (max < random_block) max = random_block;#endif#ifdef _LARGEFILE64_SOURCE if ((lseek64 (fd, (off64_t) (random_block * 512), SEEK_SET)) < 0) { perror ("IOtest: lseek64"); exit (EXIT_FAILURE); }#else if ((lseek (fd, (long) (random_block * 512), SEEK_SET)) < 0) { perror ("IOtest: lseek"); exit (EXIT_FAILURE); }#endif /* Read or Write ????????? */ /* if rwpercent = 0, this is a write only test */ /* if rwpercent = 100, this is a read only test *///.........这里部分代码省略.........
开发者ID:skizhak,项目名称:open-media-flow-controller,代码行数:101,
示例5: PAL_RandomBOOLPALAPIPAL_Random( IN BOOL bStrong, IN OUT LPVOID lpBuffer, IN DWORD dwLength){ int rand_des = -1; BOOL bRet = FALSE; DWORD i; char buf; long num = 0; static BOOL sMissingDevRandom; static BOOL sMissingDevURandom; static BOOL sInitializedMRand; PERF_ENTRY(PAL_Random); ENTRY("PAL_Random(bStrong=%d, lpBuffer=%p, dwLength=%d)/n", bStrong, lpBuffer, dwLength); i = 0; if (bStrong == TRUE && i < dwLength && !sMissingDevRandom) { // request non-blocking access to avoid hangs if the /dev/random is exhausted // or just simply broken if ((rand_des = PAL__open(RANDOM_DEVICE_NAME, O_RDONLY | O_NONBLOCK)) == -1) { if (errno == ENOENT) { sMissingDevRandom = TRUE; } else { ASSERT("PAL__open() failed, errno:%d (%s)/n", errno, strerror(errno)); } // Back off and try /dev/urandom. } else { for( ; i < dwLength; i++) { if (read(rand_des, &buf, 1) < 1) { // the /dev/random pool has been exhausted. Fall back // to /dev/urandom for the remainder of the buffer. break; } *(((BYTE*)lpBuffer) + i) ^= buf; } close(rand_des); } } if (i < dwLength && !sMissingDevURandom) { if ((rand_des = PAL__open(URANDOM_DEVICE_NAME, O_RDONLY)) == -1) { if (errno == ENOENT) { sMissingDevURandom = TRUE; } else { ASSERT("PAL__open() failed, errno:%d (%s)/n", errno, strerror(errno)); } // Back off and try mrand48. } else { for( ; i < dwLength; i++) { if (read(rand_des, &buf, 1) < 1) { // Fall back to srand48 for the remainder of the buffer. break; } *(((BYTE*)lpBuffer) + i) ^= buf; } close(rand_des); } } if (!sInitializedMRand) { srand48(time(NULL)); sInitializedMRand = TRUE; } // always xor srand48 over the whole buffer to get some randomness // in case /dev/random is not really random for(i = 0; i < dwLength; i++) {//.........这里部分代码省略.........
开发者ID:SpivEgin,项目名称:coreclr,代码行数:101,
示例6: mainintmain(int argc, char **argv){ int c; sigset_t set; const char *cfgfile = NULL; const char *jobfile = NULL; const char *defconf = "doozer-agent.json"; signal(SIGPIPE, handle_sigpipe); while((c = getopt(argc, argv, "c:s:j:")) != -1) { switch(c) { case 'c': cfgfile = optarg; break; case 's': enable_syslog("doozer-agent", optarg); break; case 'j': jobfile = optarg; break; } } sigfillset(&set); sigprocmask(SIG_BLOCK, &set, NULL); srand48(getpid() ^ time(NULL)); if(cfg_load(cfgfile, defconf)) { fprintf(stderr, "Unable to load config (check -c option). Giving up/n"); exit(1); } create_heaps(); if(geteuid() == 0) { get_uid_gid(); if(setgid(build_gid)) { trace(LOG_ERR, "Unable to setgid(%d) -- %s", build_gid, strerror(errno)); exit(1); } if(seteuid(build_uid)) { trace(LOG_ERR, "Unable to seteuid(%d) -- %s", build_uid, strerror(errno)); } } git_threads_init(); artifact_init(); agent_init(jobfile); running = 1; sigemptyset(&set); sigaddset(&set, SIGTERM); sigaddset(&set, SIGINT); sigaddset(&set, SIGHUP); signal(SIGTERM, doexit); signal(SIGINT, doexit); signal(SIGHUP, doreload); pthread_sigmask(SIG_UNBLOCK, &set, NULL); while(running) { if(reload) { reload = 0; if(!cfg_load(NULL, defconf)) { } } pause(); } spawn_stop_all(); trace(LOG_NOTICE, "Waiting for jobs to stop"); agent_join(); return 0;}
开发者ID:dreamcat4,项目名称:doozer-agent,代码行数:85,
示例7: mainint main(int argc, char *argv[]) { int i; int row; int col; time_t start; time_t finish; if (argc != 3) { fprintf(stderr, "The arguments should be ./matrix_sum size_of_matrix number_of_threads/n"); return 1; } SIZE_OF_MATRIX = atoi(argv[1]); NUMBER_OF_THREADS = atoi(argv[2]); omp_set_num_threads(NUMBER_OF_THREADS); printf("Number of procs is %d/n", omp_get_num_procs()); printf("The number of threads is %d/n", NUMBER_OF_THREADS); printf("Max number of threads is %d/n", omp_get_max_threads()); double **matrix = malloc(sizeof(double) * SIZE_OF_MATRIX); double **matrix_copy = malloc(sizeof(double) * SIZE_OF_MATRIX); double *answer_vector = malloc(sizeof(double) * SIZE_OF_MATRIX); double *answer_vector_copy = malloc(sizeof(double) * SIZE_OF_MATRIX); double *answers = malloc(sizeof(double) * SIZE_OF_MATRIX); for (i = 0; i < SIZE_OF_MATRIX; ++i) { matrix[i] = malloc(sizeof(double) * SIZE_OF_MATRIX); matrix_copy[i] = malloc(sizeof(double) * SIZE_OF_MATRIX); } srand48(time(NULL)); // seed random number fill_matrix(matrix, matrix_copy); fill_answer(answer_vector, answer_vector_copy); // Start Timing start = time(NULL); // Start elimination row = 0; col = 0; int j; for (row = 0; row < SIZE_OF_MATRIX; ++row) { pivot_on_row(row, matrix, answer_vector); #pragma omp parallel for for (i = 0; i < SIZE_OF_MATRIX; ++i) { convert_to_upper_triangle(row, matrix, answer_vector); } } back_subsitution(matrix, answer_vector, answers); // Finish Timing finish = time(NULL); double seconds = (double) difftime(finish, start); printf("Time Taken: %f/n", seconds); double l2 = 0; double total = 0; for (i = 0; i < SIZE_OF_MATRIX; ++i) { for (j = 0; j < SIZE_OF_MATRIX; ++j) { total = total + matrix_copy[i][j] * answers[j]; } l2 = l2 + pow( (total - answer_vector_copy[i]), 2); total = 0; } l2 = sqrt(l2); printf("L2 norm is %g/n", l2); free(matrix); free(matrix_copy); free(answer_vector); free(answer_vector_copy); free(answers); return 0;}
开发者ID:chansen22,项目名称:551,代码行数:84,
示例8: mainint main(int argc, char **argv) { srand(time(nullptr)); srand48(time(nullptr)); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS();}
开发者ID:sotte,项目名称:pulse-learning,代码行数:6,
示例9: mainint main(int argc, char** argv){ /* ARG PARSER *****************************************************/ std::vector<std::string> fn_input; std::string fn_output; std::string integrandName; int nPts; boostPO::variables_map vm; boostPO::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("input,i", boostPO::value(&fn_input)->composing(), "list of pointsets: each file must contains multiple pointsets with the same number of points") ("integrand,I", boostPO::value(&integrandName), "integrand function: gaussian, disk or a filename (hdr image)") ("output,o", boostPO::value(&fn_output)->required(), "output filename"); boostPO::positional_options_description p; p.add("input", -1); try { boostPO::store( boostPO::command_line_parser(argc, argv). options(desc).positional(p).run(), vm); boostPO::notify(vm); } catch(boost::program_options::error& e) { std::cerr << e.what() << std::endl; std::cout << desc << std::endl; exit(EXIT_FAILURE); } if(vm.count("help")) { std::cout << desc << std::endl; exit(EXIT_SUCCESS); } /* INIT ***********************************************************/ srand48(time(NULL)); double integrandShiftX = 0.0f; double integrandShiftY = 0.0f; IntegrandFunction integrandFunction; if(integrandName == "gaussian") { integrandFunction = gaussianFunction; integrandShiftX = 0.5; integrandShiftY = 0.5; } else if(integrandName == "disk") { integrandFunction = diskFunction; integrandShiftX = 0.5; integrandShiftY = 0.5; } else if(integrandName == "cos") { integrandFunction = cosFunction; integrandShiftX = 0.0; integrandShiftY = 0.0; } else { g_hdrFilename = integrandName; loadHdrImg(); integrandFunction = hdrFunction; integrandShiftX = 0.0; integrandShiftY = 0.0; } std::ofstream file(fn_output.c_str()); for(int n=0; n<fn_input.size(); ++n) { double nPts = 0; int iter = 0; double mean = 0; double m2 = 0; stk::io::PointSetInputStream<2, double, double> stream(fn_input[n]); do { //Read pointset stk::PointSet2dd pts; stream.read(pts); bool skip = false; if(!skip)//.........这里部分代码省略.........
开发者ID:dcoeurjo,项目名称:stk,代码行数:101,
示例10: main//.........这里部分代码省略......... else if (!strcmp(argv[i], "-")) ; else if (!strcmp(argv[i], "--nostdlib")) g->includeStdlib = false; else if (!strcmp(argv[i], "--nocpp")) g->runCPP = false;#ifndef ISPC_IS_WINDOWS else if (!strcmp(argv[i], "--pic")) generatePIC = true; else if (!strcmp(argv[i], "--colored-output")) g->forceColoredOutput = true;#endif // !ISPC_IS_WINDOWS else if (!strcmp(argv[i], "--quiet")) g->quiet = true; else if (!strcmp(argv[i], "--yydebug")) { extern int yydebug; yydebug = 1; } else if (!strcmp(argv[i], "-MMM")) { if (++i == argc) { fprintf(stderr, "No output file name specified after -MMM option./n"); usage(1); } depsFileName = argv[i]; } else if (!strcmp(argv[i], "--dev-stub")) { if (++i == argc) { fprintf(stderr, "No output file name specified after --dev-stub option./n"); usage(1); } devStubFileName = argv[i]; } else if (!strcmp(argv[i], "--host-stub")) { if (++i == argc) { fprintf(stderr, "No output file name specified after --host-stub option./n"); usage(1); } hostStubFileName = argv[i]; } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) { lPrintVersion(); return 0; } else if (argv[i][0] == '-') { fprintf(stderr, "Unknown option /"%s/"./n", argv[i]); usage(1); } else { if (file != NULL) { fprintf(stderr, "Multiple input files specified on command " "line: /"%s/" and /"%s/"./n", file, argv[i]); usage(1); } else file = argv[i]; } } // If the user specified -g, then the default optimization level is 0. // If -g wasn't specified, the default optimization level is 1 (full // optimization). if (debugSet && !optSet) g->opt.level = 0; if (g->enableFuzzTest) { if (g->fuzzTestSeed == -1) {#ifdef ISPC_IS_WINDOWS int seed = (unsigned)time(NULL);#else int seed = getpid();#endif g->fuzzTestSeed = seed; Warning(SourcePos(), "Using seed %d for fuzz testing", g->fuzzTestSeed); }#ifdef ISPC_IS_WINDOWS srand(g->fuzzTestSeed);#else srand48(g->fuzzTestSeed);#endif } if (outFileName == NULL && headerFileName == NULL && depsFileName == NULL && hostStubFileName == NULL && devStubFileName == NULL) Warning(SourcePos(), "No output file or header file name specified. " "Program will be compiled and warnings/errors will " "be issued, but no output will be generated."); return Module::CompileAndOutput(file, arch, cpu, target, generatePIC, ot, outFileName, headerFileName, includeFileName, depsFileName, hostStubFileName, devStubFileName);}
开发者ID:hgrasberger,项目名称:ispc,代码行数:101,
示例11: main/*========================================== * main *========================================== */int main(int argc, char* argv[]){ int T; // number of topics int W; // number of unique words int D; // number of docs int N; // number of words in corpus int i, iter, seed; int *w, *d, *z, *order; double **Nwt, **Ndt, *Nt; double alpha, beta; if (argc == 1) { fprintf(stderr, "usage: %s T iter seed/n", argv[0]); exit(-1); } T = atoi(argv[1]); assert(T>0); iter = atoi(argv[2]); assert(iter>0); seed = atoi(argv[3]); assert(seed>0); N = countN("docword.txt"); w = ivec(N); d = ivec(N); z = ivec(N); read_dw("docword.txt", d, w, &D, &W); Nwt = dmat(W,T); Ndt = dmat(D,T); Nt = dvec(T); alpha = 0.05 * N / (D * T); beta = 0.01; printf("seed = %d/n", seed); printf("N = %d/n", N); printf("W = %d/n", W); printf("D = %d/n", D); printf("T = %d/n", T); printf("iter = %d/n", iter); printf("alpha = %f/n", alpha); printf("beta = %f/n", beta); srand48(seed); randomassignment_d(N,T,w,d,z,Nwt,Ndt,Nt); order = randperm(N); add_smooth_d(D,T,Ndt,alpha); add_smooth_d(W,T,Nwt,beta); add_smooth1d( T,Nt, W*beta); for (i = 0; i < iter; i++) { sample_chain_d(N,W,T,w,d,z,Nwt,Ndt,Nt,order); printf("iter %d /n", i); } printf("In-Sample Perplexity = %.2f/n",pplex_d(N,W,T,w,d,Nwt,Ndt)); add_smooth_d(D,T,Ndt,-alpha); add_smooth_d(W,T,Nwt,-beta); add_smooth1d( T,Nt, -W*beta); write_sparse_d(W,T,Nwt,"Nwt.txt"); write_sparse_d(D,T,Ndt,"Ndt.txt"); write_ivec(N,z,"z.txt"); return 0;}
开发者ID:korkam,项目名称:beta_learning-matlab-through-case-studies,代码行数:72,
示例12: client_loopvoid client_loop(void){ int pages = 0; int failcnt = 0; int termcount =0; int page_ceiling; int mode = 0; srand48( time (0) ); page_ceiling = lrand48() % 40 * 1024 * 1024 / 4096; mb_register(0); while(1){ if ( pages < page_ceiling && mode == 0 ){ int ask = lrand48() % 200; int req; req = mb_request_pages ( ask ); if ( req < 0 ) { printf("transmission error/n"); exit(0); } else if (req == 0 ) { if (failcnt > 10 ){ sleep(1); failcnt = 0; mode = 1; termcount++; } else { usleep(100); } failcnt++; } else { if (req != ask){ printf ("requested %d pages, got %d/n", ask, req); failcnt++; usleep(10); } else if(termcount > 0) termcount--; pages += req; } } else if (pages > 2) { int ret = lrand48() % pages; printf ("returning %d of %d pages/n", ret, pages); if( mb_return_pages ( ret ) < 0 ) { printf ("transmission error/n"); exit(0); } else { pages -=ret; } } else { usleep(50); mode = mode == 0 ? 1:0; termcount++; } if(termcount > 10 ){ printf("failed to get pages 10 times./n"); mb_terminate(); exit(0); } }}
开发者ID:LinDing,项目名称:membroker,代码行数:68,
示例13: mainint main(int argc, char *argv[]){ struct mbus *m; char c_addr[60], *token_u[2], *token_e[2]; int seed = (gethostid() << 8) | (getpid() & 0xff), final_iters; struct timeval timeout; int i, num_sessions = 0; char **xargv = xmalloc(argc); int xargc=0;#ifdef WIN32 win32_create_null_window(); /* Needed to listen to messages */#else signal(SIGCONT, sigchld_handler); signal(SIGCHLD, sigchld_handler); signal(SIGINT, sigint_handler); signal(SIGTERM, sigint_handler); signal(SIGHUP, sigint_handler);#endif debug_msg("rat-%s started argc=%d/n", RAT_VERSION, argc); /* We have two modes: one for operation as a transcoder, one */ /* when working as a normal end-system audio tool. We choose */ /* based on the first command line argument supplied. */ if ((argc > 2) && (strcmp(argv[1], "-T") == 0)) { num_sessions = 2; } else { num_sessions = 1; } if (parse_options_early(argc, (const char**)argv) == FALSE) { return FALSE; } srand48(seed); snprintf(c_addr, 60, "(media:audio module:control app:rat id:%lu)", (unsigned long) getpid()); debug_msg("c_addr = %s/n", c_addr); m = mbus_init(mbus_control_rx, mbus_err_handler, c_addr); if (m == NULL) { fatal_error("RAT v" RAT_VERSION, "Could not initialize Mbus: Is multicast enabled?"); return FALSE; } /* pull out -X arguments */ for(i=0; i<argc; i++) { if( strcmp(argv[i],"-X") == 0 ) { xargv[xargc] = argv[i]; xargc++; i++; xargv[xargc] = argv[i]; xargc++; } } if (ui_enabled) { token_u[0] = generate_token(); fork_process(UI_NAME, c_addr, &pid_ui, 1, token_u, xargc, xargv); debug_msg("Controller waiting for %s from UI.../n", token_u[0]); if ((u_addr = mbus_rendezvous_waiting(m, "()", token_u[0], m, 20000000)) == NULL) { fatal_error("RAT v" RAT_VERSION, "MBUS Failed to rendezvous with UI - Likely firewall/VPN issue"); return FALSE; } debug_msg("Controller has rendezvous'd with UI (%s)/n",u_addr); } token_e[0] = generate_token(); token_e[1] = generate_token(); fork_process(ENGINE_NAME, c_addr, &pid_engine, num_sessions, token_e, xargc, xargv); should_exit = FALSE; for (i = 0; i < num_sessions; i++) { debug_msg("Controller waiting for %s from media engine.../n", token_e[i]); if ((e_addr[i] = mbus_rendezvous_waiting(m, "()", token_e[i], m, 20000000)) == NULL ) { fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with media engine - Likely firewall/VPN issue"); return FALSE; } debug_msg("Controller rendezvous'd with media engine (%s)/n",e_addr[i]); } if (parse_addresses(m, e_addr, argc, argv) == TRUE) { char *peer; if (ui_enabled) { if ((peer = mbus_rendezvous_go(m, token_u[0], (void *) m, 20000000)) == NULL) { fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with UI - Likely firewall/VPN issue"); return FALSE; } debug_msg("User interface is %s/n", peer); } for (i = 0; i < num_sessions; i++) { if ((peer = mbus_rendezvous_go(m, token_e[i], (void *) m, 20000000)) == NULL) { fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with UI - Likely firewall/VPN issue"); return FALSE; } debug_msg("Media engine %d is %s/n", i, peer); } debug_msg("Parsing options/n"); for (i = 0; i < num_sessions; i++) { parse_options_late(m, e_addr[i], argc, argv);//.........这里部分代码省略.........
开发者ID:amacfarlane,项目名称:rat,代码行数:101,
示例14: srandvoid srand(unsigned int x) { srand48(x); }
开发者ID:larsiusprime,项目名称:hxcpp,代码行数:1,
示例15: mainint main (int argc,char **argv ){ int generate = 0; if ( argc > 1 ) generate = 1; int lx = 4; int ly = 4; int lz = 4; int lt = 4; int nrow[4]; nrow[0] = lx; nrow[1] = ly; nrow[2] = lz; nrow[3] = lt; bfmarg dwfa; dwfa.solver = WilsonFermion; dwfa.threads = NTHREAD; dwfa.node_latt[0] = lx; dwfa.node_latt[1] = ly; dwfa.node_latt[2] = lz; dwfa.node_latt[3] = lt; dwfa.local_comm[0] = 1; dwfa.local_comm[1] = 1; dwfa.local_comm[2] = 1; dwfa.local_comm[3] = 1; dwfa.Ls = 1; dwfa.mass = 0.0; dwfa.Csw = 0.0; printf("Initialising bfm operator/n"); printf("drand48 seed = 0/n"); srand48(0); dwf.init(dwfa); psi_h = dwf.allocFermion(); chi_h = dwf.allocFermion(); check = dwf.allocFermion(); diff = dwf.allocFermion(); dwf.randFermion(psi_h); dwf.unitGauge(); printf("cb0dag0 is %lx/n",(unsigned long)cb0dag0); printf("cb0dag1 is %lx/n",(unsigned long)cb0dag1); printf("cb1dag0 is %lx/n",(unsigned long)cb1dag0); printf("cb1dag1 is %lx/n",(unsigned long)cb1dag1); // Naive Dslash // cb is cb of result, 1-cb is cb of input field int idx=0; for(cb=0;cb<2;cb++){ /*Import this checkerboard of QDP fields to bagel*/ // Fill the other checkerboard. for(dag=0;dag<2;dag++){ printf("Checking cb=%d dag=%d %lx /n",cb,dag, (unsigned long)arrays[idx]); dwf.importFermion(arrays[idx],check,0); pthread_t threads[NTHREAD]; for(int t=0;t<NTHREAD;t++){ pthread_create(&threads[t],NULL,thr_main,NULL); } for(int t=0;t<NTHREAD;t++){ pthread_join(threads[t],NULL); }#ifdef GENERATE dwf.dump(chi_h,files[idx],array_names[idx]);#else printf("Norm of difference is %le/n",delta); //printf("Norm result %le/n",n2); //printf("Norm check %le/n",n1);#endif idx++; } } printf("Done/n"); }
开发者ID:paboyle,项目名称:BFM,代码行数:91,
示例16: child_mainvoidchild_main(void){ setbuf(stdout, NULL); setbuf(stderr, NULL); printf("Child starts/n"); cache_param = heritage.param; AZ(pthread_key_create(&req_key, NULL)); AZ(pthread_key_create(&bo_key, NULL)); AZ(pthread_key_create(&name_key, NULL)); THR_SetName("cache-main"); VSM_Init(); /* First, LCK needs it. */ LCK_Init(); /* Second, locking */ Lck_New(&vxid_lock, lck_vxid); WAIT_Init(); PAN_Init(); CLI_Init(); VBF_Init(); VCL_Init(); HTTP_Init(); VDI_Init(); VBO_Init(); VBE_InitCfg(); VBP_Init(); WRK_Init(); Pool_Init(); EXP_Init(); HSH_Init(heritage.hash); BAN_Init(); VCA_Init(); SMS_Init(); SMP_Init(); STV_open(); VMOD_Init(); BAN_Compile(); srandomdev(); srand48(random()); CLI_AddFuncs(debug_cmds); /* Wait for persistent storage to load if asked to */ if (FEATURE(FEATURE_WAIT_SILO)) SMP_Ready(); Pool_Accept(); CLI_Run(); BAN_Shutdown(); STV_close(); printf("Child dies/n");}
开发者ID:1HLtd,项目名称:Varnish-Cache,代码行数:69,
示例17: bic_seq_resamplestatic void bic_seq_resample(double *tumor, int n_tumor, double *normal, int n_nml, SRM_binning args){ SEG_PERMUTE segs = NULL; int *tumor_bin, *normal_bin, nbins; int n_tumor_sample, n_normal_sample,i,k, total,start,end, kmin; double tmp, freq, N_tumor, N_normal; struct timeval tv; int seed; gettimeofday(&tv, NULL); seed = tv.tv_sec * 1000000 + tv.tv_usec; seed_set(seed); srand48(seed); segs = SEG_PERMUTE_create(args.B); tmp = tumor[n_tumor-1] > normal[n_nml-1] ? tumor[n_tumor-1]:normal[n_nml-1]; nbins = floor(tmp/args.bin_size)+10; nbins = nbins>10?nbins:10; tumor_bin = (int *) malloc(sizeof(int)*nbins); normal_bin = (int *)malloc(sizeof(int)*nbins); if(tumor_bin==NULL||normal_bin==NULL){ fprintf(stderr,"Error in bic_seq_resample: memory allocation failed/n"); exit(1); } tmp = tumor[0] < normal[0] ? tumor[0]:normal[0]; kmin = (int) floor(tmp/args.bin_size)-1; kmin = (kmin>0? kmin:0); for(i=0;i<segs->size;i++){ n_tumor_sample = rbinom(args.tumor_freq,n_tumor+n_nml); n_normal_sample = rbinom(1-args.tumor_freq,n_tumor+n_nml); random_sample(tumor, n_tumor, normal, n_nml, n_tumor_sample, args.bin_size ,tumor_bin, nbins, args.paired, args.insert, args.sd); random_sample(tumor, n_tumor, normal, n_nml, n_normal_sample, args.bin_size ,normal_bin,nbins, args.paired, args.insert, args.sd); N_tumor=0.0; N_normal = 0.0; for(k=kmin;k<nbins;k++){ start = k*args.bin_size+1; end = start+args.bin_size; total = tumor_bin[k] + normal_bin[k]; freq = ((double) tumor_bin[k])/((double) total); if(total>0) ll_append(segs->bins_perm[i], bin_new(tumor_bin[k], total, freq, start, end)); N_tumor += tumor_bin[k]; N_normal += normal_bin[k]; } set_BinList(segs->bins_perm[i]); set_totalreadcount(N_tumor,N_normal); if(args.autoselect_lambda!=1){ bic_seq(args.paired); //bic_seq(0); }else{ bic_seq_auto(ll_length(segs->bins_perm[i]),args.FP,args.paired); //bic_seq_auto(ll_length(segs->bins_perm[i]),args.FP,0); } segs->bins_perm[i] = get_BinList(); } print_SEG_PERMUTE(segs,args.output); SEG_PERMUTE_destroy(segs); segs = NULL; free(tumor_bin); tumor_bin = NULL; free(normal_bin);normal_bin = NULL; return;}
开发者ID:daviddliu,项目名称:THetA_luigi,代码行数:66,
示例18: mainint main(int argc, const char *argv[]){ // Seed the random number generator using time srand48((unsigned int) time(NULL)); // Dimension of the operation with defaul value int N = PROBSIZE; // Specify operation: 0 MatMult; 1 MatVecMult int opr = 0; // Whether to verify the result or not int verif = 0; // Whether to display the result or not int disp = 0; // Whether to call the naive implementation int execNaive = 1; // Whether to call the optimized implementation int execOPT = 1; // Parse command line { int arg_index = 1; int print_usage = 0; while (arg_index < argc) { if ( strcmp(argv[arg_index], "-N") == 0 ) { arg_index++; N = atoi(argv[arg_index++]); } else if ( strcmp(argv[arg_index], "-operation") == 0 ) { arg_index++; opr = atoi(argv[arg_index++]); } else if ( strcmp(argv[arg_index], "-help") == 0 ) { print_usage = 1; break; } else if( strcmp(argv[arg_index], "-verif") == 0 ) { arg_index++; verif = 1; if(execNaive==0 || execOPT==0) { printf("***Must call both naive and optimized when running verification/n"); print_usage = 1; break; } } else if( strcmp(argv[arg_index], "-disp") == 0 ) { arg_index++; disp = 1; } else if( strcmp(argv[arg_index], "-naive") == 0 ) { arg_index++; execNaive = 1; execOPT = 0; if(verif==1) { printf("***Must call both naive and optimized when running verification/n"); print_usage = 1; break; } } else if( strcmp(argv[arg_index], "-OPT") == 0 ) { arg_index++; execOPT = 1; execNaive = 0; if(verif==1) { printf("***Must call both naive and optimized when running verification/n"); print_usage = 1; break; } } else { printf("***Invalid argument: %s/n", argv[arg_index]); print_usage = 1; break; } } if (print_usage) { printf("/n"); printf("Usage: %s [<options>]/n", argv[0]); printf("/n"); printf(" -N <N> : problem size (default: %d)/n", PROBSIZE); printf(" -operation <ID> : Operation ID = 0 for MatMult or ID = 1 for MatVecMult/n"); printf(" -verif : Activate verification/n"); printf(" -disp : Display result (use only for small N!)/n"); printf(" -naive : Run only naive implementation/n");//.........这里部分代码省略.........
开发者ID:jean-sebastien-dery,项目名称:ECSE425-Final-Project,代码行数:101,
示例19: mainint main(int argc, char *argv [ ]){ long int ppp=1111990911; time_t seconds; time( & seconds ) ; srand ( seconds ) ; srand48 ( seconds ) ; //srand generates a sequence of random numbers depending upon the seed value FILE *p1; //p1 = fopen ( argv [ 1 ],"w" ) ; int NoIteration = atoi ( argv [ 1 ] ) ; //TAM_WIDTH_MAX = atoi ( argv [ 3 ] ) ; int iteration; long int t,mint; FILE *tamread; tamread = fopen("tam_testtime.txt","r"); for(int ii = 0; ii< SIZE; ii++) tam_testtime[ii].no_of_tam = TAM_INFO[ii]; for(int ii = 0; ii< SIZE; ii++) { for(int jj = 0; jj< tam_testtime[ii].no_of_tam; jj++) { fscanf(tamread,"%d/t%ld", &tam_testtime[ii].tam_list[jj], &tam_testtime[ii].testtime_list[jj]); } } fclose (tamread); /*temp_tam_index[0] = TAM_INFO[0]; for(int i = 1; i< SIZE; i++) { temp_tam_index[i] = temp_tam_index[i-1]+TAM_INFO[i]; } */ if(HARD_DIE_TEST) { initialiseparticle(&(partarray[0])); partarray[0].time_fitness = bin_packing(partarray[0].info,0,0); // printf("%ld /n", partarray[0].time_fitness); for ( int i = 0 ; i < SIZE ; i ++ ) { //printf ("{ %d, %d, %ld, %ld, %d }/n", scheduler[0][i].corenum, scheduler[0][i].tam_width, scheduler[0][i]. starttime, scheduler[0][i]. endtime, scheduler[0][i]. tsv); } print_csv(partarray[0].time_fitness, scheduler[0]); return 0; } for(iteration=0;iteration < NoIteration;iteration++) { globalbestIndx = 0; mint=particle_swarm_optimization(); //printf ("Globalbestindx: %d/n",globalbestIndx); /*fo/r ( int pp = 0 ; pp < SIZE ; pp ++ ){ BestParticle [ pp ] .tam_width = scheduler [globalbestIndx][pp]. tam_width; BestParticle [ pp ] .corenum = scheduler [globalbestIndx][pp]. corenum; BestParticle [ pp ] .starttime = scheduler [globalbestIndx][pp]. starttime; BestParticle [ pp ] .endtime = scheduler [globalbestIndx][pp]. endtime; }*/ for(int i=1;i<3;i++) { //printf("RunForrestRun: %d/n",i); globalbestIndx = 0; t=particle_swarm_optimization(); /*for ( int ii = 0 ; ii < SIZE ; ii ++ ) { printf ("{ %d, %d, %ld, %ld }/n", scheduler [globalbestIndx][ii].corenum, scheduler [globalbestIndx][ii].tam_width, scheduler [globalbestIndx][ii]. starttime, scheduler [globalbestIndx][ii]. endtime); }*/ if ( t < mint ) { mint = t ; /*for ( int pp = 0 ; pp < SIZE ; pp ++ ){ BestParticle [ pp ] .corenum = scheduler [globalbestIndx][pp]. corenum; BestParticle [ pp ] .tam_width = scheduler [globalbestIndx][pp]. tam_width; BestParticle [ pp ] .starttime = scheduler [globalbestIndx][pp]. starttime; BestParticle [ pp ] .endtime = scheduler [globalbestIndx][pp]. endtime; }*/ } //printf("%ld /n",t); } //fprintf(p1,"%ld/n",mint); //printf("%ld/n",mint); } for ( int i = 0 ; i < SIZE ; i ++ ) { //printf ("{ %d, %d, %ld, %ld, %d }/n", BestParticle[i].corenum, BestParticle[i].tam_width, BestParticle[i]. starttime, BestParticle[i]. endtime, BestParticle[i]. tsv); } print_csv(mint, BestParticle); return 0;}
开发者ID:nilmadhab,项目名称:BTP,代码行数:97,
示例20: main//.........这里部分代码省略......... ReadChannelState(Dump.InitStatePath, &(Time.Start), ChannelData.streams); } InitSnowMap(&Map, &SnowMap); InitAggregated(Veg.MaxLayers, Soil.MaxLayers, &Total); InitModelState(&(Time.Start), &Map, &Options, PrecipMap, SnowMap, SoilMap, Soil, SType, VegMap, Veg, VType, Dump.InitStatePath, SnowAlbedo, TopoMap, Network, &HydrographInfo, Hydrograph); InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap, RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, Dump.InitStatePath); InitNewDay(Time.Current.JDay, &SolarGeo); if (NGraphics > 0) { printf("Initialzing X11 display and graphics /n"); InitXGraphics(argc, argv, Map.NY, Map.NX, NGraphics, &MetMap); } shade_offset = FALSE; if (Options.Shading == TRUE) shade_offset = TRUE; /* Done with initialization, delete the list with input strings */ DeleteList(Input); /***************************************************************************** Sediment Initialization Procedures *****************************************************************************/ if(Options.Sediment) { time (&tloc); srand48 (tloc); /* Randomize Random Generator */ /* Commenting the line above and uncommenting the line below allows for the comparison of scenarios. */ /* srand48 (0); */ printf("/nSTARTING SEDIMENT INITIALIZATION PROCEDURES/n/n"); ReadInitFile(Options.SedFile, &Input); InitParameters(Input, &Options, &Map, &Network, &ChannelData, TopoMap, &Time, SedDiams); InitSedimentTables(Time.NDaySteps, Input, &SedType, &SType, &VType, &Soil, &Veg); InitFineMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, &FineMap); if (Options.HasNetwork){ printf("Initializing channel sediment/n/n"); InitChannelSedimentDump(&ChannelData, Dump.Path, Options.ChannelRouting); InitChannelSediment(ChannelData.streams, &Total); InitChannelSediment(ChannelData.roads, &Total); } InitSedMap( &Map, &SedMap); /* Done with initialization, delete the list with input strings */ DeleteList(Input); }
开发者ID:michaeco,项目名称:DHSVM,代码行数:66,
示例21: throw//*****************************************************************void PVFSProjector::projectPVFS(BaseProgress * progress) throw(ProjectorException){ MPI_Status status; int msize(0), membersize(0), position(0); long int buffersize(0); unsigned char * buffer(0); //the bufer for sending Stitcher * mystitch(0); //stitcher pointer long int beginofchunk(0), endofchunk(0); //for passing to the slave long int chunkcounter(0); //for output long int ycounter(1); int chunkdif(maxchunk-minchunk); try { //init the status progress if (progress) { std::strstream tempstream; tempstream << "Reprojecting " << newheight << " lines." << std::ends; tempstream.freeze(0); progress->init(tempstream.str(), NULL, "Done.", newheight, 29); progress->start(); //start the progress } if (stitcher) //see if we want a stitcher { //creates the stitcher thread if (!(mystitch = new (std::nothrow) Stitcher(out))) throw std::bad_alloc(); } //figure out the maximum buffer size based on the system; MPI_Pack_size(2, MPI_LONG, MPI_COMM_WORLD, &membersize); buffersize+=membersize; MPI_Pack_size(maxchunk*newwidth*spp, MPI_UNSIGNED_CHAR, MPI_COMM_WORLD, &membersize); buffersize+=membersize; //ask for the buffer if (!(buffer = new unsigned char[buffersize])) throw std::bad_alloc(); if (sequencemethod == 2) //init the random number srand48(time(NULL)); while (chunkcounter < newheight) { //do a blocking wait for any message. MPI_Recv(buffer, buffersize, MPI_PACKED, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); //get the starting scanline beginofchunk = mcounters[membership[status.MPI_SOURCE]]; //check termination if (beginofchunk < 0) { //terminate the slave chunkcounter += terminateSlave(status, mystitch, buffer, buffersize); } else { //check the sequence method switch(sequencemethod) { case 0: endofchunk = beginofchunk + maxchunk-1; break; case 1: ++ycounter; if (ycounter >= sequencesize) ycounter = 0; endofchunk = beginofchunk + sequence[ycounter]-1; break; case 2: endofchunk = beginofchunk + static_cast<int>(drand48()*chunkdif + minchunk) -1; break; } //check to see if this is the last chunk in the partition if (endofchunk >= mstop[membership[status.MPI_SOURCE]]-1) { endofchunk = mstop[membership[status.MPI_SOURCE]]-1; //reset the counter mcounters[membership[status.MPI_SOURCE]] = -1;//.........这里部分代码省略.........
开发者ID:briangmaddox,项目名称:USGS-MPIProject,代码行数:101,
示例22: mainint main(int argc, char* argv[]){ int niter = 100000; //number of iterations per FOR loop int myid; //hold's process's rank id double x,y; //x,y value for the random coordinate int i; //loop counter int count=0; //Count holds all the number of how many good coordinates double z; //Used to check if x^2+y^2<=1 double pi; //holds approx value of pi int reducedcount; //total number of "good" points from all nodes int reducedniter; //total number of ALL points from all nodes int ranknum = 0; //total number of nodes available int numthreads = 16 //edit this number to change the number of OpenMP threads launched per MPI task MPI_Init(&argc, &argv); //Start MPI MPI_Comm_rank(MPI_COMM_WORLD, &myid); //get rank of node's process MPI_Comm_size(MPI_COMM_WORLD, &ranknum); //Gets number of nodes availible to process if(myid != 0) //Do the following on all except the master node { //Start OpenMP code: 16 threads/node #pragma omp parallel firstprivate(x, y, z, i) reduction(+:count) num_threads(numthreads) { srand48((int)time(NULL) ^ omp_get_thread_num()); //Give drand48() a seed value for (i=0; i<niter; ++i) //main loop { x = (double)drand48();//RAND_MAX; //gets a random x coordinate y = (double)drand48();//RAND_MAX; //gets a random y coordinate z = ((x*x)+(y*y)); //Checks to see if number is inside unit square if (z<=1) { ++count; //if it is, consider it a valid random point } } //print the value of each thread/rank } } MPI_Barrier(MPI_COMM_WORLD); /*Use MPI_Reduce() to get all the values of count and add them together (MPI_SUM) and return it to * reducedcount * The reason MPI_Reduce is used here is because its a more streamlined way of gathering together all count data * into one variable and performing an operation on it. Its also possible to use MPI_Send() and MPI_Recv(), but * it tends to make the code less readable in my opinion, though it could possibly make it faster since its not * an all-to-one communication like MPI_Reduce() is; while MPI_Send() and MPI_Recv() is a one to one * comm unication */ MPI_Reduce(&count, &reducedcount, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); /*Since, from the point of view of the code, you know the number of iterations per loop/thread/node is, you can * calculate it without using an MPI routine like above. * 16 threads with niter iterations each on (the number of nodes - the master node) nodes */ reducedniter = numthreads*niter*(ranknum-1); MPI_Barrier(MPI_COMM_WORLD); if (myid == 0) //if root process/master node { //p = 4(m/n) | Compute the ratio of good hits to bad hits (monte carlo) pi = ((double)reducedcount/(double)reducedniter)*4.0; //Print the calculated value of pi printf("Pi: %f/n", pi); } MPI_Finalize(); //Close the MPI instance return 0;}
开发者ID:frenchrd,项目名称:Serial-to-Parallel--Monte-Carlo-Pi,代码行数:62,
示例23: init_rand_seedvoid init_rand_seed( long int seed ){ if( seed == 0 ) seed = (long)time(NULL)+(long)getpid() ; srand48(seed) ;}
开发者ID:neurodebian,项目名称:afni_removeme_eventually,代码行数:5,
示例24: mainint main(int argc, char **argv){ if (argc < 2) { printf("Usage:/n"); printf(" %s port_no [loss_rate]/n", argv[0]); exit(1); } // Seed the RNG from is_lost() srand48(12345); // Parse/validate args char *port = argv[1]; printf("port = %s/n", port); long int x = strtol(argv[1], NULL, 10); if (x < 0 || x > USHRT_MAX) { fprintf(stderr, "[error]: port %ld is invalid/n", x); exit(1); } double loss_rate = 0.0; if (argc == 3) { loss_rate = strtof(argv[2], NULL); if (loss_rate < 0.0 || loss_rate > 1.0) { fprintf(stderr, "[error]: loss_rate must be between 0 and 1/n"); exit(1); } } // Get a socket to connect to int sock; struct sockaddr their_addr; if (get_addr_sock(&their_addr, &sock, NULL, port) == -1) { fprintf(stderr, "[error]: unable to get socket/n"); exit(1); } // Len of connecting address socklen_t addrlen = (socklen_t) sizeof(their_addr); // Last packet received int packet_received = -1; // Buffer to store data in char *buf = malloc((strlen(g_buffer) + 1) * sizeof(char)); char *bufstart = buf; // Main loop of execution - runs until we get an error or tear-down msg while (true) { // Receive a packet struct packet_t pkt; if (recv_packet(&pkt, sock, &their_addr, &addrlen, loss_rate) == -1) { fprintf(stderr, "[receiver]: couldn't receive packet/n"); exit(1); } // Check if this is the tear-down message. If so, get out of loop. if (pkt.type == 4) { printf("RECEIVED TEAR-DOWN PACKET/n"); break; } // Check if this is the next packet in the sequence. If so, adjust // packet_received appropriately and copy data to the buffer else if (pkt.seq_no == (packet_received + 1)) { packet_received++; strcpy(bufstart, pkt.data); bufstart += pkt.len; } printf("RECEIVED PACKET %d/n", pkt.seq_no); // Send ACK struct ack_t ack; if (make_ack(&ack, 2, packet_received) == -1) { fprintf(stderr, "[receiver]: couldn't construct ACK/n"); exit(1); } if (send_ack(&ack, sock, &their_addr) == -1) { fprintf(stderr, "[receiver]: couldn't send ACK %d/n", ack.ack_no); exit(1); } printf("--------SEND ACK %d/n", ack.ack_no + 1); printf("/n"); } // Construct ACK to tear-down message and send struct ack_t tear_down_ack; if (make_ack(&tear_down_ack, 8, 0) == -1) { fprintf(stderr, "[receiver]: couldn't construct tear-down ACK/n"); exit(1); } if (send_ack(&tear_down_ack, sock, &their_addr) == -1) { fprintf(stderr, "[receiver]: couldn't send tear-down ACK/n"); exit(1); } printf("--------SEND TEAR-DOWN ACK/n"); // Timer for 7 seconds. Additionally, set a timeout on the socket so that // we don't exceed the timeout by not receiving any packets if (set_timeout(sock, 7) == -1) {//.........这里部分代码省略.........
开发者ID:get9,项目名称:GoBackNProtocol,代码行数:101,
示例25: mainint main(int argc, char* argv[]){ // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // instantiate LivesBoard, centered in middle of window, above Scoreboard. GLabel liveslabel = initLivesBoard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; // ball movement double ball_vertical = 2.0; double ball_horizontal = 2 * drand48(); bool godmode = false; if (argc > 2) { return 1; } // detect god mode if ((argc == 2) && (strcmp(argv[1], "GOD") == 0)) { godmode = true; } waitForClick(); // keep playing until game over while (lives > 0 && bricks > 0) { // call detectCollision func to check for collisions GObject object = detectCollision(window, ball); // ball collision with paddle if (object == paddle) { ball_vertical = -ball_vertical; } // detect collision with bricks if (object != NULL) { if (strcmp(getType(object), "GRect") == 0 && object != paddle) { removeGWindow(window, object); ball_vertical = -ball_vertical; points++; bricks--; updateScoreboard(window, label, points); if (bricks == 0) { printf("YOU WON! :)/n"); } } } // ball collision with bottom edge if (getY(ball) >= getHeight(window)) { lives--; updateLivesboard(window, liveslabel, lives); setLocation(ball, BALL_X, BALL_Y); setLocation(paddle, PADDLE_X, PADDLE_Y); waitForClick(); if (lives == 0) { printf("GAME OVER :(/n"); } } // if godmode is on, set paddle-x equal to ball-x if (godmode == true) { setLocation(paddle, getX(ball) + (BALL_WIDTH / 2) - (PADDLE_WIDTH / 2), PADDLE_Y); } else { //.........这里部分代码省略.........
开发者ID:flxio,项目名称:CS50,代码行数:101,
示例26: mainint main ( int argc , char **argv ){ int i, j, m1, m2, bw, n ; int loops, m ; long int seed ; double *coeffs, *signal, *newcoeffs; double *wigners, *wignersTrans ; double *workspace, *scratch ; double *weights ; double *sinPts, *cosPts ; double *sinPts2, *cosPts2 ; double tmp_error, sum_error; double tmp_relerror, sum_relerror; double tstartA, tstopA, runtimeA ; double tstartB, tstopB, runtimeB ; double *relerror, *curmax; double ave_error, ave_relerror, stddev_error, stddev_relerror ; FILE *fp ; if (argc < 5) { fprintf(stdout,"Usage: test_Wigner_Naive m1 m2 bw loops [output_file]/n"); exit(0); } m1 = atoi( argv[1] ); m2 = atoi( argv[2] ); bw = atoi( argv[3] ); loops = atoi( argv[4] ) ; m = MAX( ABS( m1 ) , ABS( m2 ) ) ; n = 2 * bw ; runtimeA = 0.0 ; runtimeB = 0.0 ; weights = ( double * ) malloc(sizeof( double ) * (2*bw) ) ; coeffs = ( double * ) malloc(sizeof( double ) * (bw - m) ) ; newcoeffs = ( double * ) malloc(sizeof( double ) * (bw - m) ) ; signal = ( double * ) malloc(sizeof( double ) * n ) ; wigners = ( double * ) malloc( sizeof( double ) * ( bw - m ) * n ) ; wignersTrans = ( double * ) malloc( sizeof( double ) * ( bw - m ) * n ) ; workspace = (double *) malloc(sizeof( double ) * (4 + 6) * n ) ; sinPts = workspace ; cosPts = sinPts + n ; sinPts2 = cosPts + n ; cosPts2 = sinPts2 + n ; scratch = cosPts2 + n ; /* scratch needs to be of size 6*n */ /* note that the definition of wigSpec requires that instead of evaluating at beta, I need to evaluate at beta/2; ergo I call SinEvalPts2 instead of SinEvalPts, etc etc */ /* generate seed for random number generator */ time ( &seed ) ; srand48( seed ) ; /* precompute sines and cosines appropriate for making the wigners */ SinEvalPts( n, sinPts ) ; CosEvalPts( n, cosPts ) ; SinEvalPts2( n, sinPts2 ) ; CosEvalPts2( n, cosPts2 ) ; /* make quadrature weights */ makeweights2( bw, weights ); /* make the wigners */ genWig_L2( m1, m2, bw, sinPts, cosPts, sinPts2, cosPts2, wigners, scratch ) ; /* now make the wigners - transpose version! */ genWigTrans_L2( m1, m2, bw, sinPts, cosPts, sinPts2, cosPts2, wignersTrans, scratch ) ; /** space for errors **/ relerror = (double *) malloc(sizeof(double) * loops); curmax = (double *) malloc(sizeof(double) * loops); sum_error = 0.0 ; sum_relerror = 0.0 ; for ( i = 0 ; i < loops ; i ++ ) { /* generate random coeffs */ for( j = 0 ; j < (bw - m) ; j++ ) coeffs[ j ] = drand48() ; /* turn on stop watch */ tstartA = csecond () ; /* now synthesize */ wigNaiveSynthesis( m1, m2, bw, coeffs,//.........这里部分代码省略.........
开发者ID:artivis,项目名称:soft20,代码行数:101,
示例27: mainint main(int argc, char **argv){ long int i, N; bool already_invaded; N = atoi(argv[1]); threshold = atof(argv[2]); srand48(atoi(argv[3])); Site start; start.loc = std::make_pair(0, 0); start.weight = 0; invadedSites.insert(start); for (int neigh=0;neigh<4; neigh++) { Bond newBond; double newStrength = drand48(); newBond = std::make_pair(newStrength, std::make_pair(start, get_neighbor(start, neigh))); accessibleBonds.insert(std::make_pair(newStrength, newBond)); } while(!accessibleBonds.empty()) { BondMap::iterator weakest; weakest = accessibleBonds.begin(); accessibleBonds.erase(weakest); invade_bond(weakest->second); i++; if(i == N) { accessibleBonds.clear(); } } std::stringstream fileName; fileName << "fractures" << argv[3] << ".txt"; std::ofstream toFile1(fileName.str().c_str(), std::ios::trunc);// std::ofstream toFile2("trapped.txt", std::ios::trunc); toFile1 << growth.size() << "/n";// toFile2 << trapped.size() << "/n";// toFile1 << "Invasion for: temp" << "/n";// toFile2 << "Trapping for: temp" << "/n";// toFile1.precision(17);// toFile2.precision(17);//// Bond current_Line;// while (!growth.empty())// {// current_Line = growth.front();// growth.pop_front();// toFile1 << current_Line.first << "/t";// toFile1 << current_Line.second.first.loc.first << "/t";// toFile1 << current_Line.second.first.loc.second << "/t";// toFile1 << current_Line.second.second.loc.first << "/t";// toFile1 << current_Line.second.second.loc.second << "/n";// }////// while (!trapped.empty())// {// current_Line = trapped.front();// trapped.pop_front();// toFile2 << current_Line.first << "/t";// toFile2 << current_Line.second.first.loc.first << "/t";// toFile2 << current_Line.second.first.loc.second << "/t";// toFile2 << current_Line.second.second.loc.first << "/t";// toFile2 << current_Line.second.second.loc.second << "/n";// }//// toFile1.close();// toFile2.close(); return 0;}
开发者ID:jqnorris,项目名称:InvasionPercolation,代码行数:74,
示例28: bwa_bwtsw2int bwa_bwtsw2(int argc, char *argv[]){ bsw2opt_t *opt; bwt_t *target[2]; char buf[1024]; bntseq_t *bns; int c; opt = bsw2_init_opt(); srand48(11); while ((c = getopt(argc, argv, "q:r:a:b:t:T:w:d:z:m:y:s:c:N:Hf:")) >= 0) { switch (c) { case 'q': opt->q = atoi(optarg); break; case 'r': opt->r = atoi(optarg); break; case 'a': opt->a = atoi(optarg); break; case 'b': opt->b = atoi(optarg); break; case 'w': opt->bw = atoi(optarg); break; case 'T': opt->t = atoi(optarg); break; case 't': opt->n_threads = atoi(optarg); break; case 'z': opt->z = atoi(optarg); break; case 'y': opt->yita = atof(optarg); break; case 's': opt->is = atoi(optarg); break; case 'm': opt->mask_level = atof(optarg); break; case 'c': opt->coef = atof(optarg); break; case 'N': opt->t_seeds = atoi(optarg); break; case 'H': opt->hard_clip = 1; break; case 'f': freopen(optarg, "w", stdout); } } opt->qr = opt->q + opt->r; if (optind + 2 > argc) { fprintf(stderr, "/n"); fprintf(stderr, "Usage: bwa bwasw [options] <target.prefix> <query.fa>/n/n"); fprintf(stderr, "Options: -a INT score for a match [%d]/n", opt->a); fprintf(stderr, " -b INT mismatch penalty [%d]/n", opt->b); fprintf(stderr, " -q INT gap open penalty [%d]/n", opt->q); fprintf(stderr, " -r INT gap extension penalty [%d]/n", opt->r);// fprintf(stderr, " -y FLOAT error recurrence coef. (4..16) [%.1f]/n", opt->yita); fprintf(stderr, "/n"); fprintf(stderr, " -t INT nmber of threads [%d]/n", opt->n_threads); fprintf(stderr, " -s INT size of a chunk of reads [%d]/n", opt->chunk_size); fprintf(stderr, "/n"); fprintf(stderr, " -w INT band width [%d]/n", opt->bw); fprintf(stderr, " -m FLOAT mask level [%.2f]/n", opt->mask_level); fprintf(stderr, "/n"); fprintf(stderr, " -T INT score threshold divided by a [%d]/n", opt->t); fprintf(stderr, " -s INT maximum seeding interval size [%d]/n", opt->is); fprintf(stderr, " -z INT Z-best [%d]/n", opt->z); fprintf(stderr, " -N INT # seeds to trigger reverse alignment [%d]/n", opt->t_seeds); fprintf(stderr, " -c FLOAT coefficient of length-threshold adjustment [%.1f]/n", opt->coef); fprintf(stderr, " -H in SAM output, use hard clipping rather than soft/n"); fprintf(stderr, " -f FILE file to output results to instead of stdout/n"); fprintf(stderr, "/n"); { double c, theta, eps, delta; c = opt->a / log(opt->yita); theta = exp(-opt->b / c) / opt->yita; eps = exp(-opt->q / c); delta = exp(-opt->r / c); fprintf(stderr, "mismatch: %lf, gap_open: %lf, gap_ext: %lf/n/n", theta, eps, delta); } return 1; } // adjust opt for opt->a opt->t *= opt->a; opt->coef *= opt->a; strcpy(buf, argv[optind]); target[0] = bwt_restore_bwt(strcat(buf, ".bwt")); strcpy(buf, argv[optind]); bwt_restore_sa(strcat(buf, ".sa"), target[0]); strcpy(buf, argv[optind]); target[1] = bwt_restore_bwt(strcat(buf, ".rbwt")); strcpy(buf, argv[optind]); bwt_restore_sa(strcat(buf, ".rsa"), target[1]); bns = bns_restore(argv[optind]); bsw2_aln(opt, bns, target, argv[optind+1]); bns_destroy(bns); bwt_destroy(target[0]); bwt_destroy(target[1]); free(opt); return 0;}
开发者ID:fiber-miniapp,项目名称:ngsa-mini,代码行数:85,
注:本文中的srand48函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 C++ srandom函数代码示例 C++ srand函数代码示例 |