int main(int argc, char *argv[]) { int compare_size = COMPARE_SIZE; unsigned int maxerr = COMPARE_THRESHOLD; if (argc < 3) { fprintf(stdout, "\nERROR: Not enough arguments\n"); usage(); exit(1); } char *sql_info = argv[1]; int portno = atoi(argv[2]); if (!portno) { fprintf(stdout, "\nERROR: Invalid port\n"); usage(); exit(1); } // Work out how many CPUs we have. Default to 2 global_cpu_count = get_cpu_count(stdout); if (global_cpu_count == 0) { global_cpu_count = 2; } MagickWandGenesis(); server_loop(stdout, sql_info, portno, compare_size, maxerr); MagickWandTerminus(); /* The final thing that main() should do */ pthread_exit(NULL); exit(0); }
void sched_init (void) { int j, i; for (j = 0; j < get_cpu_count(); j++) { SYSINFO_A_ASSIGN(si_percpu_ticks,j,0); SYSINFO_A_ASSIGN(si_percpu_idle_ticks,j,0); LIST_INIT (&(__cpucxts[j]->_qfreelist)); for (i = 0; i < NQUANTUM; i++) { __cpucxts[j]->_qvec[i].q_no = i; __cpucxts[j]->_qvec[i].q_used = 0; LIST_INSERT_HEAD (&(__cpucxts[j]->_qfreelist), &(__cpucxts[j]->_qvec[i]), q_link); } /* current quantum must start at 1 since the scheduling loop that uses * this will skip the idle process and run each process once before * giveing out new ticks to each quantum. */ __cpucxts[j]->_current_q = 1; __cpucxts[j]->_in_revocation = 0; to_list[j] = NULL; } }
ThreadPoolImpl::ThreadPoolImpl(int numThreads) : m_ok(false) , m_referenceCount(1) , m_firstProvider(NULL) , m_lastProvider(NULL) { if (numThreads == 0) numThreads = get_cpu_count(); char *buffer = new char[sizeof(PoolThread) * numThreads]; m_threads = reinterpret_cast<PoolThread*>(buffer); m_numThreads = numThreads; if (m_threads) { m_ok = true; for (int i = 0; i < numThreads; i++) { new (buffer)PoolThread(*this); buffer += sizeof(PoolThread); m_ok = m_ok && m_threads[i].start(); } // Wait for threads to spin up and idle while (PoolThread::s_sleepCount < m_numThreads) { GIVE_UP_TIME(); } } }
int update_cpu_usage() { size_t size; unsigned int i; /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ if ((cpu_setup == 0) || (!info.cpu_usage)) { get_cpu_count(); cpu_setup = 1; } if (info.cpu_count > 1) { size = CPUSTATES * sizeof(int64_t); for (i = 0; i < info.cpu_count; i++) { int cp_time_mib[] = { CTL_KERN, KERN_CPTIME2, i }; if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, NULL, 0) < 0) { NORM_ERR("sysctl kern.cp_time2 failed"); } } } else { int cp_time_mib[] = { CTL_KERN, KERN_CPTIME }; long cp_time_tmp[CPUSTATES]; size = sizeof(cp_time_tmp); if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, NULL, 0) < 0) { NORM_ERR("sysctl kern.cp_time failed"); } for (i = 0; i < CPUSTATES; i++) { fresh[i] = (int64_t) cp_time_tmp[i]; } } /* XXX Do sg with this int64_t => long => double ? float hell. */ for (i = 0; i < info.cpu_count; i++) { int64_t used, total; int at = i * CPUSTATES; used = fresh[at + CP_USER] + fresh[at + CP_NICE] + fresh[at + CP_SYS]; total = used + fresh[at + CP_IDLE]; if ((total - oldtotal[i]) != 0) { info.cpu_usage[i] = ((double) (used - oldused[i])) / (double) (total - oldtotal[i]); } else { info.cpu_usage[i] = 0; } oldused[i] = used; oldtotal[i] = total; } return 0; }
void vp8_machine_specific_config(VP8_COMMON *ctx) { #if CONFIG_MULTITHREAD ctx->processor_core_count = get_cpu_count(); #endif /* CONFIG_MULTITHREAD */ #if ARCH_ARM ctx->cpu_caps = arm_cpu_caps(); #elif ARCH_X86 || ARCH_X86_64 ctx->cpu_caps = x86_simd_caps(); #endif }
void setup_workers() { int r; exepath_for_worker(); char* args[2]; args[0] = exepath; args[1] = NULL; round_robin_counter = 0; int cpu_count = get_cpu_count(); child_worker_count = cpu_count; workers = calloc(sizeof(struct child_worker), cpu_count); while (cpu_count--) { struct child_worker *worker = &workers[cpu_count]; // pipe is acting as IPC channel uv_pipe_init(loop, &worker->pipe, IPC); // https://github.com/thlorenz/libuv-dox/blob/master/types.md#uv_stdio_container_t // https://github.com/thlorenz/libuv-dox/blob/master/types.md#uv_stdio_flags uv_stdio_container_t child_stdio[3]; child_stdio[STDIN].flags = UV_CREATE_PIPE | UV_READABLE_PIPE; child_stdio[STDIN].data.stream = (uv_stream_t*) &worker->pipe; child_stdio[STDOUT].flags = UV_IGNORE; child_stdio[STDERR].flags = UV_INHERIT_FD; child_stdio[STDERR].data.fd = STDERR; // https://github.com/thlorenz/libuv-dox/blob/master/types.md#uv_process_options_t worker->options.stdio_count = 3; worker->options.stdio = child_stdio; worker->options.exit_cb = on_exit; worker->options.file = exepath; worker->options.args = args; r = uv_spawn(loop, &worker->req, &worker->options); if (r) ERROR("spawning worker", r); fprintf(stderr, "Started worker %d\n", worker->req.pid); } }
bool Movie::Setup() { if (!IsRecording()) return false; if (!av) return false; bool success = true; std::string err_msg; alephone::Screen *scr = alephone::Screen::instance(); view_rect = scr->window_rect(); if (MainScreenIsOpenGL()) view_rect.y = scr->height() - (view_rect.y + view_rect.h); view_rect.x *= scr->pixel_scale(); view_rect.y *= scr->pixel_scale(); view_rect.w *= scr->pixel_scale(); view_rect.h *= scr->pixel_scale(); temp_surface = SDL_CreateRGBSurface(SDL_SWSURFACE, view_rect.w, view_rect.h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0); success = (temp_surface != NULL); if (!success) err_msg = "Could not create SDL surface"; Mixer *mx = Mixer::instance(); av_register_all(); avcodec_register_all(); // Open output file AVOutputFormat *fmt; if (success) { fmt = av_guess_format("webm", NULL, NULL); success = fmt; if (!success) err_msg = "Could not find output format"; } if (success) { av->fmt_ctx = avformat_alloc_context(); success = av->fmt_ctx; if (!success) err_msg = "Could not allocate movie format context"; } if (success) { av->fmt_ctx->oformat = fmt; strncpy(av->fmt_ctx->filename, moviefile.c_str(), 1024); success = (0 <= avio_open(&av->fmt_ctx->pb, av->fmt_ctx->filename, AVIO_FLAG_WRITE)); if (!success) err_msg = "Could not open movie file for writing"; } // Open output video stream AVCodec *video_codec; AVStream *video_stream; if (success) { video_codec = avcodec_find_encoder(AV_CODEC_ID_VP8); success = video_codec; if (!success) err_msg = "Could not find VP8 encoder"; } if (success) { video_stream = avformat_new_stream(av->fmt_ctx, video_codec); success = video_stream; if (!success) err_msg = "Could not open output video stream"; } if (success) { video_stream->codec->codec_id = video_codec->id; video_stream->codec->codec_type = AVMEDIA_TYPE_VIDEO; video_stream->codec->width = view_rect.w; video_stream->codec->height = view_rect.h; video_stream->codec->time_base = (AVRational){1, TICKS_PER_SECOND}; video_stream->codec->pix_fmt = AV_PIX_FMT_YUV420P; video_stream->codec->flags |= CODEC_FLAG_CLOSED_GOP; video_stream->codec->thread_count = get_cpu_count(); if (av->fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) video_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; av->video_stream_idx = video_stream->index; // tuning options int vq = graphics_preferences->movie_export_video_quality; video_stream->codec->bit_rate = ScaleQuality(vq, 100*1024, 1024*1024, 10*1024*1024); video_stream->codec->qmin = ScaleQuality(vq, 10, 4, 0); video_stream->codec->qmax = ScaleQuality(vq, 63, 63, 50); std::string crf = boost::lexical_cast<std::string>(ScaleQuality(vq, 63, 10, 4)); av_opt_set(video_stream->codec->priv_data, "crf", crf.c_str(), 0); success = (0 <= avcodec_open2(video_stream->codec, video_codec, NULL)); if (!success) err_msg = "Could not open video codec"; } if (success) { av->video_bufsize = view_rect.w * view_rect.h * 4 + 10000; av->video_buf = static_cast<uint8_t *>(av_malloc(av->video_bufsize)); success = av->video_buf; if (!success) err_msg = "Could not allocate video buffer"; } if (success) { #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,0) av->video_frame = avcodec_alloc_frame(); #else av->video_frame = av_frame_alloc(); #endif success = av->video_frame; if (!success) err_msg = "Could not allocate video frame"; } if (success) { int numbytes = avpicture_get_size(video_stream->codec->pix_fmt, view_rect.w, view_rect.h); av->video_data = static_cast<uint8_t *>(av_malloc(numbytes)); success = av->video_data; if (!success) err_msg = "Could not allocate video data buffer"; } if (success) { avpicture_fill(reinterpret_cast<AVPicture *>(av->video_frame), av->video_data, video_stream->codec->pix_fmt, view_rect.w, view_rect.h); } // Open output audio stream AVCodec *audio_codec; AVStream *audio_stream; if (success) { audio_codec = avcodec_find_encoder(AV_CODEC_ID_VORBIS); success = audio_codec; if (!success) err_msg = "Could not find Vorbis encoder"; } if (success) { audio_stream = avformat_new_stream(av->fmt_ctx, audio_codec); success = audio_stream; if (!success) err_msg = "Could not open output audio stream"; } if (success) { audio_stream->codec->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; audio_stream->codec->codec_id = audio_codec->id; audio_stream->codec->codec_type = AVMEDIA_TYPE_AUDIO; audio_stream->codec->sample_rate = mx->obtained.freq; audio_stream->codec->time_base = (AVRational){1, mx->obtained.freq}; audio_stream->codec->channels = 2; if (av->fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) audio_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; av->audio_stream_idx = audio_stream->index; // tuning options int aq = graphics_preferences->movie_export_audio_quality; audio_stream->codec->global_quality = FF_QP2LAMBDA * (aq / 10); audio_stream->codec->flags |= CODEC_FLAG_QSCALE; audio_stream->codec->sample_fmt = AV_SAMPLE_FMT_FLTP; success = (0 <= avcodec_open2(audio_stream->codec, audio_codec, NULL)); if (!success) err_msg = "Could not open audio codec"; } if (success) { #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,0) av->audio_frame = avcodec_alloc_frame(); #else av->audio_frame = av_frame_alloc(); #endif success = av->audio_frame; if (!success) err_msg = "Could not allocate audio frame"; } if (success) { av->audio_fifo = av_fifo_alloc(262144); success = av->audio_fifo; if (!success) err_msg = "Could not allocate audio fifo"; } if (success) { av->audio_data = reinterpret_cast<uint8_t *>(av_malloc(524288)); success = av->audio_data; if (!success) err_msg = "Could not allocate audio data buffer"; } if (success) { av->audio_data_conv = reinterpret_cast<uint8_t *>(av_malloc(524288)); success = av->audio_data_conv; if (!success) err_msg = "Could not allocate audio conversion buffer"; } // initialize conversion context if (success) { av->sws_ctx = sws_getContext(temp_surface->w, temp_surface->h, AV_PIX_FMT_RGB32, video_stream->codec->width, video_stream->codec->height, video_stream->codec->pix_fmt, SWS_BILINEAR, NULL, NULL, NULL); success = av->sws_ctx; if (!success) err_msg = "Could not create video conversion context"; } // Start movie file if (success) { video_stream->time_base = (AVRational){1, TICKS_PER_SECOND}; audio_stream->time_base = (AVRational){1, mx->obtained.freq}; avformat_write_header(av->fmt_ctx, NULL); } // set up our threads and intermediate storage if (success) { videobuf.resize(av->video_bufsize); audiobuf.resize(2 * 2 * mx->obtained.freq / 30); } if (success) { encodeReady = SDL_CreateSemaphore(0); fillReady = SDL_CreateSemaphore(1); stillEncoding = true; success = encodeReady && fillReady; if (!success) err_msg = "Could not create movie thread semaphores"; } if (success) { encodeThread = SDL_CreateThread(Movie_EncodeThread, "MovieSetup_encodeThread", this); success = encodeThread; if (!success) err_msg = "Could not create movie encoding thread"; } if (!success) { StopRecording(); std::string full_msg = "Your movie could not be exported. ("; full_msg += err_msg; full_msg += ".)"; logError(full_msg.c_str()); alert_user(full_msg.c_str()); } av->inited = success; return success; }
int HT_SetAffinity() { unsigned long mask; pid_t pid; int result=1; int cpu_count, i, j, k, cpuid; pid=getpid(); tst_resm(TINFO, "Set affinity through system call.\n"); cpu_count=get_cpu_count(); if(cpu_count==0) { return 0; } else if(cpu_count>32) cpu_count=32; for(i=0, mask=0x1;i<cpu_count;i++, mask=mask<<1) { tst_resm(TINFO, "Set test process affinity."); printf("mask: %x\n",mask); sched_setaffinity(pid, sizeof(unsigned long), &mask); for(j=0;j<10;j++) { for(k=0;k<10;k++) { if(fork()==0) { system("ps > /dev/null"); exit(0); } } sleep(1); if(get_current_cpu(pid)!=i) break; } if(j<10) { tst_resm(TINFO, "...Error\n"); result=0; } else tst_resm(TINFO, "...OK\n"); } for(i=0, mask=0x3;i<cpu_count-1;i++, mask=mask<<1) { tst_resm(TINFO, "Set test process affinity."); printf("mask: %x\n",mask); sched_setaffinity(pid, sizeof(unsigned long), &mask); for(j=0;j<10;j++) { for(k=0;k<10;k++) { if(fork()==0) { system("ps > /dev/null"); exit(0); } } sleep(1); cpuid=get_current_cpu(pid); if(cpuid!=i&&cpuid!=i+1) break; } if(j<10) { tst_resm(TINFO, "...Error\n"); result=0; } else tst_resm(TINFO, "...OK\n"); } if(result) return 1; else return 0; }
int main(void) { int stdin_size; char *stdin_mem = read_stdin(&stdin_size); int cpu_count = get_cpu_count(); char output_buffer[7][MAX_OUTPUT]; # define DECLARE_PARAM(o, n) {\ .start = stdin_mem, \ .length = stdin_size, \ .frame = n,\ .output = output_buffer[o],\ .output_size = MAX_OUTPUT } struct print_freqs_param freq_params[2] = { DECLARE_PARAM(0, 1), DECLARE_PARAM(1, 2) }; # undef DECLARE_PARAM # define DECLARE_PARAM(o, s) {\ .start = stdin_mem, \ .length = stdin_size, \ .nuc_seq = s,\ .output = output_buffer[o],\ .output_size = MAX_OUTPUT } struct print_occurences_param occurences_params[5] = { DECLARE_PARAM(2, "GGT"), DECLARE_PARAM(3, "GGTA"), DECLARE_PARAM(4, "GGTATT"), DECLARE_PARAM(5, "GGTATTTTAATT"), DECLARE_PARAM(6, "GGTATTTTAATTTATAGT") }; # undef DECLARE_PARAM struct tp *tp = tp_create(7); for (int i = 0 ; i < 2; i++) { tp_add_job(tp, &print_freqs, &freq_params[i]); } for (int i = 0 ;i < 5; i++) { tp_add_job(tp, &print_occurences, &occurences_params[i]); } tp_run(tp, cpu_count + 1); tp_destroy(tp); for (int i = 0; i < 2; i++) { printf("%s\n", output_buffer[i]); } for (int i = 2; i < 7; i++) { printf("%s", output_buffer[i]); } free(stdin_mem); return 0; }
int main(int argc, char **argv) { int rank, size, i; int root = 0; int hits = 0; // index used for 'hits' int total = 1; // index used for 'total' int msg_waiting = 0; double results[2] = {0}; MPI_Init(&argc, &argv); MPI_Comm comm = MPI_COMM_WORLD; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); MPI_Status status; MPI_Request request; // is root process if(rank == root) { double area; double total_hits = 0; double total_pokes = 0; while (1) { // check each slave process for results (non-blocking) for (i = 1; i < size; i++) { MPI_Iprobe(i, 0, comm, &msg_waiting, &status); // if slave process is sending results if (msg_waiting) { MPI_Recv(&results, 2, MPI_DOUBLE, i, 0, comm, &status); total_hits += results[hits]; total_pokes += results[total]; } } if (total_pokes >= 15000000000) { area = (total_hits / total_pokes) * 4; printf("Area=%.12lf\n", area); // send terminating message to each slave process for (i = 1; i < size; i++) { MPI_Isend(&area, 1, MPI_DOUBLE, i, 0, comm, &request); } break; } } // is slave process } else { int cpu_count = get_cpu_count(); double shared_results[cpu_count * 2]; double l_hits = 0; double l_total = 0; pthread_t threads[cpu_count]; t_data thread_data[cpu_count]; for (i = 0; i < cpu_count; i++) { thread_data[i].id = i; thread_data[i].rank = rank; thread_data[i].results = shared_results; pthread_create(&threads[i], NULL, &throw_darts, &thread_data[i]); } // periodically reads results from shared memory; sends to root process while(1) { sleep(3); // first checks for termination flag from root process MPI_Iprobe(root, 0, comm, &msg_waiting, &status); if (msg_waiting) { // terminate threads for (i = 0; i < cpu_count; i++) { pthread_cancel(threads[i]); } break; } else { results[hits] = 0; results[total] = 0; for (i = 0; i < cpu_count; i++) { results[hits] += shared_results[i * 2]; results[total] += shared_results[i * 2 + 1]; } results[hits] -= l_hits; results[total] -= l_total; l_hits += results[hits]; l_total += results[total]; // send results to root process MPI_Isend(&results, 2, MPI_DOUBLE, root, 0, comm, &request); } } } MPI_Finalize(); return 0; }
int HT_InterruptDistribution() { FILE *pFile; int ci[32],cj[32]; int cpucount, i; int cmax, cmin, d; tst_resm(TINFO, "Get interrupts distribution with HT."); if ((cpucount=get_cpu_count())<=0) { return 0; } if ((pFile=fopen(INTERRUPT_NAME, "r"))==NULL) { return 0; } fgets(buf, 255, pFile); fscanf(pFile, "%s %d %d %d %d %d %d %d %d \ %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d \ %d %d %d %d %d %d %d %d", buf, ci, ci+1, ci+2, ci+3, ci+4, ci+5, ci+6, ci+7, ci+8, ci+9, ci+10, ci+11, ci+12, ci+13, ci+14, ci+15, ci+16, ci+17, ci+18, ci+19, ci+20, ci+21, ci+22, ci+23, ci+24, ci+25, ci+26, ci+27, ci+28, ci+29, ci+30, ci+31); fclose(pFile); for (i=0;i<10;i++) { sleep(1); printf("."); } if ((pFile=fopen(INTERRUPT_NAME, "r"))==NULL) { return 0; } fgets(buf, 255, pFile); fscanf(pFile, "%s %d %d %d %d %d %d %d %d \ %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d \ %d %d %d %d %d %d %d %d", buf, cj, cj+1, cj+2, cj+3, cj+4, cj+5, cj+6, cj+7, cj+8, cj+9, cj+10, cj+11, cj+12, cj+13, cj+14, cj+15, cj+16, cj+17, cj+18, cj+19, cj+20, cj+21, cj+22, cj+23, cj+24, cj+25, cj+26, cj+27, cj+28, cj+29, cj+30, cj+31); fclose(pFile); printf("\n\n"); printf("Timer interrupt counts per CPU:\n"); d=cj[0]-ci[0]; printf("%d ", d); cmax=cmin=d; for (i=1;i<cpucount;i++) { d=cj[i]-ci[i]; printf("%d ", d); if (cmax<d) cmax=d; if (cmin>d) cmin=d; } printf("\n\n"); printf("max value: %d\n", cmax); printf("min value: %d\n", cmin); printf("\n"); if (cmin==0 || cmax/cmin>10) { return 0; } else { return 1; } }
bool InitSystem(void) { setlocale(LC_ALL, ""); systemData.locale = QLocale::system(); systemData.locale.setNumberOptions(QLocale::OmitGroupSeparator); QLocale::setDefault(systemData.locale); QTextStream out(stdout); systemData.homedir = QDir::homePath() + QDir::separator(); #ifdef WIN32 /* WINDOWS */ systemData.sharedDir = (QDir::currentPath() + QDir::separator()); #else systemData.sharedDir = QString(SHARED_DIR) + QDir::separator(); #endif /* WINDOWS */ //logfile #ifdef WIN32 /* WINDOWS */ systemData.logfileName = systemData.homedir + "mandelbulber_log.txt"; #else systemData.logfileName = systemData.homedir + ".mandelbulber_log.txt"; #endif FILE *logfile = fopen(systemData.logfileName.toUtf8().constData(), "w"); fclose(logfile); out << "Mandelbulber " << MANDELBULBER_VERSION_STRING << ", build date: " << QString(__DATE__) << "\n"; out << "Log file name: " << systemData.logfileName << endl; WriteLogString("Mandelbulber version", QString(MANDELBULBER_VERSION_STRING)); WriteLogString("Mandelbulber compilation date", QString(__DATE__) + " " + QString(__TIME__)); //detecting number of CPU cores systemData.numberOfThreads = get_cpu_count(); //NR_THREADS = 1; printf("Detected %d CPUs\n", systemData.numberOfThreads); WriteLogDouble("CPUs detected", systemData.numberOfThreads); #ifdef ONETHREAD //for debugging NR_THREADS = 1; #endif //data directory location #ifdef WIN32 /* WINDOWS */ systemData.dataDirectory = systemData.homedir + "mandelbulber" + QDir::separator(); #else systemData.dataDirectory = systemData.homedir + ".mandelbulber" + QDir::separator(); #endif out << "Default data directory: " << systemData.dataDirectory << endl; WriteLogString("Default data directory", systemData.dataDirectory); systemData.thumbnailDir = systemData.dataDirectory + "thumbnails" + QDir::separator(); systemData.autosaveFile = systemData.dataDirectory + ".autosave.fract"; //*********** temporary set to false ************ systemData.noGui = false; systemData.lastSettingsFile = systemData.dataDirectory + "settings" + QDir::separator() + QString("settings.fract"); systemData.lastImageFile = systemData.dataDirectory + "images" + QDir::separator() + QString("image.jpg"); systemData.lastImagePaletteFile = systemData.sharedDir + "textures" + QDir::separator() + QString("colour palette.jpg"); QLocale systemLocale = QLocale::system(); systemData.decimalPoint = systemLocale.decimalPoint(); WriteLogString("Decimal point", QString(systemData.decimalPoint)); systemData.supportedLanguages.insert("en_EN", "English"); systemData.supportedLanguages.insert("pl_PL", "Polski"); systemData.supportedLanguages.insert("de_DE", "Deutsch"); systemData.supportedLanguages.insert("it_IT", "Italiano"); //get number of columns of console #ifdef WIN32 systemData.terminalWidth = 80; #else handle_winch(-1); #endif return true; }
int main(int argc, char *argv[]) { char *broker_ip = strdup("127.0.0.1"); int recv_port = 5562; int send_port = 5561; int run_seconds = 10; int num_channels = 50; int msg_size = 20; int num_clients = get_cpu_count() / 2; num_clients = num_clients > 0 ? num_clients : 1; int verbose = 0; int opt; while ((opt = getopt(argc, argv, "b:r:s:t:S:C:vh")) != -1) { switch (opt) { case 'b': free(broker_ip); broker_ip = strdup(optarg); break; case 'r': recv_port = atoi(optarg); break; case 's': send_port = atoi(optarg); break; case 't': run_seconds = atoi(optarg); break; case 'S': msg_size = atoi(optarg); break; case 'C': num_clients = atoi(optarg); break; case 'v': verbose = 1; break; case 'h': usage(); exit(EXIT_SUCCESS); default: fprintf(stderr, "Try 'nanomsg_pubsub_cliet -h' for more information"); exit(EXIT_FAILURE); } } int i; char **channels = (char **) malloc(sizeof(char *) * num_channels); for (i = 0; i < num_channels; i++) { channels[i] = (char *) malloc(SIZE8); memset(channels[i], '\0', SIZE8); sprintf(channels[i], "%d", i); } pubsub_info *info = (pubsub_info *) malloc(sizeof(pubsub_info)); info->broker_ip = broker_ip; info->recv_port = recv_port; info->send_port = send_port; info->msg_size = msg_size; info->num_channels = num_channels; info->channels = channels; info->verbose = verbose; pthread_t *pub_threads = (pthread_t *) malloc(sizeof(pthread_t) * num_clients); for (i = 0; i < num_clients; i++) { pthread_create(&pub_threads[i], NULL, publisher, (void *)info); } sleep(1); pthread_t *sub_threads = (pthread_t *) malloc(sizeof(pthread_t) * num_clients); for (i = 0; i < num_clients; i++) { pthread_create(&sub_threads[i], NULL, subscriber, (void *)info); } int rc; int metrics_fd; metrics_fd = nn_socket(AF_SP, NN_SUB); assert(metrics_fd != -1); char sub_addr[SIZE32]; rc = sprintf(sub_addr, "tcp://%s:%d", broker_ip, send_port); sub_addr[rc] = '\0'; rc = nn_connect(metrics_fd, sub_addr); assert(rc >= 0); rc = nn_setsockopt(metrics_fd, NN_SUB, NN_SUB_SUBSCRIBE, "metrics", 7); assert(rc == 0); INT64 start, now; get_timestamp(&start); int *stats = (int *) malloc(sizeof(int) * num_clients * run_seconds); int cnt = 0; while (1) { get_timestamp(&now); if (now - start > run_seconds * 1000) { break; } char *msg = NULL; int bytes = nn_recv(metrics_fd, &msg, NN_MSG, 0); assert (bytes >= 0); char *start = strchr(msg, ' ') + 1; stats[cnt++] = atoi(start); nn_freemsg (msg); } printf("%d median msg/sec\n", get_median(stats, cnt)); free(broker_ip); free(info); free(stats); printf("done!\n"); return 0; }
void update_cpu_usage() { #ifdef OLDCPU int mib[2] = { CTL_KERN, KERN_CPTIME }; long used, total; long cp_time[CPUSTATES]; size_t len = sizeof(cp_time); #else size_t size; unsigned int i; #endif /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ if ((cpu_setup == 0) || (!info.cpu_usage)) { get_cpu_count(); cpu_setup = 1; } #ifdef OLDCPU if (sysctl(mib, 2, &cp_time, &len, NULL, 0) < 0) { NORM_ERR("Cannot get kern.cp_time"); } fresh.load[0] = cp_time[CP_USER]; fresh.load[1] = cp_time[CP_NICE]; fresh.load[2] = cp_time[CP_SYS]; fresh.load[3] = cp_time[CP_IDLE]; fresh.load[4] = cp_time[CP_IDLE]; used = fresh.load[0] + fresh.load[1] + fresh.load[2]; total = fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3]; if ((total - oldtotal) != 0) { info.cpu_usage[0] = ((double) (used - oldused)) / (double) (total - oldtotal); } else { info.cpu_usage[0] = 0; } oldused = used; oldtotal = total; #else if (info.cpu_count > 1) { size = CPUSTATES * sizeof(int64_t); for (i = 0; i < info.cpu_count; i++) { int cp_time_mib[] = { CTL_KERN, KERN_CPTIME2, i }; if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, NULL, 0) < 0) { NORM_ERR("sysctl kern.cp_time2 failed"); } } } else { int cp_time_mib[] = { CTL_KERN, KERN_CPTIME }; long cp_time_tmp[CPUSTATES]; size = sizeof(cp_time_tmp); if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, NULL, 0) < 0) { NORM_ERR("sysctl kern.cp_time failed"); } for (i = 0; i < CPUSTATES; i++) { fresh[i] = (int64_t) cp_time_tmp[i]; } } /* XXX Do sg with this int64_t => long => double ? float hell. */ for (i = 0; i < info.cpu_count; i++) { int64_t used, total; int at = i * CPUSTATES; used = fresh[at + CP_USER] + fresh[at + CP_NICE] + fresh[at + CP_SYS]; total = used + fresh[at + CP_IDLE]; if ((total - oldtotal[i]) != 0) { info.cpu_usage[i] = ((double) (used - oldused[i])) / (double) (total - oldtotal[i]); } else { info.cpu_usage[i] = 0; } oldused[i] = used; oldtotal[i] = total; } #endif }
int main(int argc, char* argv[]) { int rv = 0; int cpu_count = 0; int init_length = 0; int code_length = 0; int seq_length = 0; char* s_cstr = NULL; Tcl_Interp *tcl = NULL; Tcl_Obj* s = NULL; /* Initialize Tcl. */ Tcl_FindExecutable(argv[0]); tcl = Tcl_CreateInterp(); Tcl_Preserve((ClientData)tcl); /* Count the number of cpus. If the cpu count could not be * determined, assume 4 cpus. */ cpu_count = get_cpu_count(); if (!cpu_count) { cpu_count = 4; } /* Allocate s. */ s = Tcl_NewStringObj("", 0); Tcl_IncrRefCount(s); /* Load stdin into s. */ load_file(stdin, s); /* Get the length of s. */ init_length = Tcl_GetCharLength(s); /* Strip off section headers and EOLs from s. This is a little * messy because we have to go from Tcl-string to C-string and * back to Tcl-string. */ s_cstr = regsub("(>.*)|\n", Tcl_GetString(s), "", NULL); Tcl_SetStringObj(s, s_cstr, strlen(s_cstr)); g_free(s_cstr); s_cstr = NULL; /* Get the length of s. */ code_length = Tcl_GetCharLength(s); /* Process the variants by counting them and printing the results. */ process_variants(cpu_count, s); /* Substitute nucleic acid codes in s with their meanings. */ process_nacodes(cpu_count, s); /* Get the length of s. */ seq_length = Tcl_GetCharLength(s); /* Print the lengths. */ printf("\n%d\n%d\n%d\n", init_length, code_length, seq_length); /* Clean up. */ Tcl_DecrRefCount(s); /* Finalize Tcl. */ Tcl_Release((ClientData)tcl); Tcl_Exit(rv); /* Not reached. */ return rv; }
void vp8_machine_specific_config(VP8_COMMON *ctx) { #if CONFIG_RUNTIME_CPU_DETECT VP8_COMMON_RTCD *rtcd = &ctx->rtcd; rtcd->dequant.block = vp8_dequantize_b_c; rtcd->dequant.idct_add = vp8_dequant_idct_add_c; rtcd->dequant.idct_add_y_block = vp8_dequant_idct_add_y_block_c; rtcd->dequant.idct_add_uv_block = vp8_dequant_idct_add_uv_block_c; rtcd->idct.idct16 = vp8_short_idct4x4llm_c; rtcd->idct.idct1_scalar_add = vp8_dc_only_idct_add_c; rtcd->idct.iwalsh1 = vp8_short_inv_walsh4x4_1_c; rtcd->idct.iwalsh16 = vp8_short_inv_walsh4x4_c; rtcd->recon.copy16x16 = vp8_copy_mem16x16_c; rtcd->recon.copy8x8 = vp8_copy_mem8x8_c; rtcd->recon.copy8x4 = vp8_copy_mem8x4_c; rtcd->recon.build_intra_predictors_mby = vp8_build_intra_predictors_mby; rtcd->recon.build_intra_predictors_mby_s = vp8_build_intra_predictors_mby_s; rtcd->recon.build_intra_predictors_mbuv = vp8_build_intra_predictors_mbuv; rtcd->recon.build_intra_predictors_mbuv_s = vp8_build_intra_predictors_mbuv_s; rtcd->recon.intra4x4_predict = vp8_intra4x4_predict_c; rtcd->subpix.sixtap16x16 = vp8_sixtap_predict16x16_c; rtcd->subpix.sixtap8x8 = vp8_sixtap_predict8x8_c; rtcd->subpix.sixtap8x4 = vp8_sixtap_predict8x4_c; rtcd->subpix.sixtap4x4 = vp8_sixtap_predict_c; rtcd->subpix.bilinear16x16 = vp8_bilinear_predict16x16_c; rtcd->subpix.bilinear8x8 = vp8_bilinear_predict8x8_c; rtcd->subpix.bilinear8x4 = vp8_bilinear_predict8x4_c; rtcd->subpix.bilinear4x4 = vp8_bilinear_predict4x4_c; rtcd->loopfilter.normal_mb_v = vp8_loop_filter_mbv_c; rtcd->loopfilter.normal_b_v = vp8_loop_filter_bv_c; rtcd->loopfilter.normal_mb_h = vp8_loop_filter_mbh_c; rtcd->loopfilter.normal_b_h = vp8_loop_filter_bh_c; rtcd->loopfilter.simple_mb_v = vp8_loop_filter_simple_vertical_edge_c; rtcd->loopfilter.simple_b_v = vp8_loop_filter_bvs_c; rtcd->loopfilter.simple_mb_h = vp8_loop_filter_simple_horizontal_edge_c; rtcd->loopfilter.simple_b_h = vp8_loop_filter_bhs_c; #if CONFIG_POSTPROC || (CONFIG_VP8_ENCODER && CONFIG_INTERNAL_STATS) rtcd->postproc.down = vp8_mbpost_proc_down_c; rtcd->postproc.across = vp8_mbpost_proc_across_ip_c; rtcd->postproc.downacross = vp8_post_proc_down_and_across_c; rtcd->postproc.addnoise = vp8_plane_add_noise_c; rtcd->postproc.blend_mb_inner = vp8_blend_mb_inner_c; rtcd->postproc.blend_mb_outer = vp8_blend_mb_outer_c; rtcd->postproc.blend_b = vp8_blend_b_c; #endif #endif #if ARCH_X86 || ARCH_X86_64 vp8_arch_x86_common_init(ctx); #endif #if ARCH_ARM vp8_arch_arm_common_init(ctx); #endif #if CONFIG_MULTITHREAD ctx->processor_core_count = get_cpu_count(); #endif /* CONFIG_MULTITHREAD */ }
int chudnovsky(int digits, int threads) { int res = 0; unsigned long int i, iter, precision, rest, per_cpu, k; mpf_t ltf, sum, result; pthread_t *pthreads; struct thread_args targs; mp_exp_t exponent; char *pi; /* If threads is not specified, check how many CPUs are avail */ if (threads == 0) { threads = get_cpu_count(); } pthreads = malloc(threads * sizeof(pthread_t)); if (pthreads == NULL) { res = -ENOMEM; goto chudnovsky_exit; } /* Calculate and set precision */ precision = (digits * BPD) + 1; mpf_set_default_prec(precision); /* Calculate number of iterations */ iter = digits/DPI + 1; /* Init all objects */ mpf_inits(ltf, sum, result, targs.sum, NULL); mpf_set_ui(sum, 0); mpf_set_ui(targs.sum, 0); /* Set pthread specific stuff */ targs.k = 0; targs.iter = iter; pthread_mutex_init(&targs.start_mutex, NULL); pthread_mutex_init(&targs.sum_mutex, NULL); /* Prepare the constant from the left side of the equation */ mpf_sqrt_ui(ltf, LTFCON1); mpf_mul_ui(ltf, ltf, LTFCON2); printf("Starting summing, using:\n" "%d digits - %lu iterations - %d threads\n", digits, iter, threads); for (i = 0; i < threads; i++) { pthread_create(&pthreads[i], NULL, &chudnovsky_chunk, (void *) &targs); } /* Wait for threads to finish and take their sums */ for (i = 0; i < threads; i++) { pthread_join(pthreads[i], NULL); } printf("Starting final steps\n"); /* Invert sum */ mpf_ui_div(sum, 1, targs.sum); mpf_mul(result, sum, ltf); /* Get one more char then needed and then trunc to avoid rounding */ pi = mpf_get_str(NULL, &exponent, 10, digits + 2, result); pi[digits+1] = '\0'; if (strlen(pi) < LAST_DIGITS_PRINT + 1) { printf("Calculated PI:\n"); printf("\t%.*s.%s\n", (int)exponent, pi, pi + exponent); } else { printf("Last digits of Pi are:\n"); printf("\t%s\n", pi+(digits-(LAST_DIGITS_PRINT-1))); } free(pi); mpf_clears(ltf, sum, result, NULL); pthread_mutex_destroy(&targs.start_mutex); pthread_mutex_destroy(&targs.sum_mutex); /* TODO: add verification here! */ chudnovsky_free_pthreads: free(pthreads); chudnovsky_exit: return res; }