当前位置: 首页>>代码示例>>C++>>正文


C++ program函数代码示例

本文整理汇总了C++中program函数的典型用法代码示例。如果您正苦于以下问题:C++ program函数的具体用法?C++ program怎么用?C++ program使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了program函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main

/*----------------------------------------------------------------------------*/
int main(void)
{
  static const uint32_t address = 0;
  uint8_t buffer[384];

  for (size_t i = 0; i < sizeof(buffer); ++i)
    buffer[i] = i;

  const struct Pin led = pinInit(LED_PIN);
  pinOutput(led, false);

  struct Interface * const eeprom = init(Eeprom, 0);
  assert(eeprom);

  uint32_t size;
  enum Result res;

  pinSet(led);
  if ((res = ifGetParam(eeprom, IF_SIZE, &size)) == E_OK)
    pinReset(led);
  assert(res == E_OK);

  assert(address < size);

  pinSet(led);
  if ((res = program(eeprom, buffer, sizeof(buffer), address)) == E_OK)
    pinReset(led);
  assert(res == E_OK);

  pinSet(led);
  if ((res = verify(eeprom, buffer, sizeof(buffer), address)) == E_OK)
    pinReset(led);
  assert(res == E_OK);

  while (1);
  return 0;
}
开发者ID:stxent,项目名称:halm-examples,代码行数:38,代码来源:main.c

示例2: main

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setOrganizationName("Innovators");
    app.setApplicationName("TrollEdit");
    app.setStartDragDistance(app.startDragDistance() * 2);

    // set splashScreen
    QPixmap pixmap(":/splash");
    QSplashScreen splashScreen(pixmap,Qt::WindowStaysOnTopHint);

    // find the directory of the program
    QFileInfo program(argv[0]);
    QString path = QApplication::applicationDirPath();

    MainWindow w(path);

    w.setWindowOpacity(0);

    splashScreen.show();
 
    w.setWindowIcon (QIcon(":/icon16"));
    w.show();

    QTimer::singleShot(2000, &splashScreen, SLOT(close()));
    QTimer::singleShot(1000, &w, SLOT(wInit()));
    // open all files given as parameters

    //    w.newFile();
    //    w.open("../input/in.c"); // TEMP
    
    // open all files given as parameters
    for (int i = 1; i < argc; i++)
        w.open(argv[i]);

    return app.exec();
}
开发者ID:brathm,项目名称:TrollEdit,代码行数:37,代码来源:main.cpp

示例3: main

int main(int argc, char *argv[])
{
	const char *outfilename = "tinyL.out";
	char *input;
	FILE *infile;

	printf("------------------------------------------------\n");
	printf("CS314 compiler for tinyL\n");
	printf("------------------------------------------------\n");

	if (argc != 2) {
		fprintf(stderr, "Use of command:\n  compile <tinyL file>\n");
		exit(EXIT_FAILURE);
	}

	infile = fopen(argv[1], "r");
	if (!infile) {
		ERROR("Cannot open input file \"%s\"\n", argv[1]);
		exit(EXIT_FAILURE);
	}
	outfile = fopen(outfilename, "w");
	if (!outfile) {
		ERROR("Cannot open output file \"%s\"\n", outfilename);
		exit(EXIT_FAILURE);
	}

	input = read_input(infile);
	buffer = input;
	program();

	printf("\nCode written to file \"%s\".\n\n", outfilename);

	free(input);
	fclose(infile);
	fclose(outfile);
	return EXIT_SUCCESS;
}
开发者ID:jcierpial,项目名称:LL1-Parser,代码行数:37,代码来源:Compiler.c

示例4: Q_UNUSED

void QSGVideoMaterialShader_YUV_BiPlanar::updateState(const RenderState &state,
                                                      QSGMaterial *newMaterial,
                                                      QSGMaterial *oldMaterial)
{
    Q_UNUSED(oldMaterial);

    QSGVideoMaterial_YUV *mat = static_cast<QSGVideoMaterial_YUV *>(newMaterial);
    program()->setUniformValue(m_id_plane1Texture, 0);
    program()->setUniformValue(m_id_plane2Texture, 1);

    mat->bind();

    program()->setUniformValue(m_id_colorMatrix, mat->m_colorMatrix);
    program()->setUniformValue(m_id_plane1Width, mat->m_planeWidth[0]);
    program()->setUniformValue(m_id_plane2Width, mat->m_planeWidth[1]);
    if (state.isOpacityDirty()) {
        mat->m_opacity = state.opacity();
        program()->setUniformValue(m_id_opacity, GLfloat(mat->m_opacity));
    }
    if (state.isMatrixDirty())
        program()->setUniformValue(m_id_matrix, state.combinedMatrix());
}
开发者ID:MarianMMX,项目名称:MarianMMX,代码行数:22,代码来源:qsgvideonode_yuv.cpp

示例5: main

int main(int argc, char* argv[]) {
  int *oargv, i, result;

  oargv = (int*)malloc(sizeof(int) + sizeof(int*) * argc);
  oargv[0] = argc;

  for (i=0; i<argc; i++){
    int len, j;
    char *p;

    len = strlen(argv[i]);
    p = (char*)malloc(sizeof(int) + sizeof(char) * (len + 1));
    *((int*)p) = len;
    for (j=0; j<len; j++){
      p[sizeof(int)+j] = argv[i][j];
    }    
    p[sizeof(int)+len] = 0;
    oargv[1+i] = (int)(p+4);
  }

  result = program(argc, oargv+1);
  printf("%d\n", result);
  return result;
}
开发者ID:awbraunstein,项目名称:OAT-Compiler,代码行数:24,代码来源:runtime.c

示例6: TEST

TEST(Logical, op_ori)
{
    tememu::MipsCPU cpu;
    boost::shared_ptr< std::vector<int32> > program(new std::vector<int32>);

    program->push_back(0x34a7ffff); // ori $a3, $a1, 65535 
    cpu.loadProgram(program);

    cpu.setGPR(5, 0xffffffff);
    cpu.runProgram();
    EXPECT_EQ(cpu.gprValue(7), 0xffffffff);

    cpu.reset();

    cpu.setGPR(5, 0x00000000);
    cpu.runProgram();
    EXPECT_EQ(cpu.gprValue(7), 0x0000ffff);

    cpu.reset(); 

    cpu.setGPR(5, 0xff00ff00);
    cpu.runProgram();
    EXPECT_EQ(cpu.gprValue(7), 0xff00ffff);
}
开发者ID:sztomi,项目名称:tememu,代码行数:24,代码来源:main.cpp

示例7: program

QString CoreInterface::run(const QStringList& args, const QString& input)
{
	QString program(
		QCoreApplication::applicationDirPath()
		+ "/" + kCoreBinary);

	QProcess process;
	process.setReadChannel(QProcess::StandardOutput);
	process.start(program, args);
	bool success = process.waitForStarted();

	QString output, error;
	if (success)
	{
		if (!input.isEmpty()) {
			process.write(input.toStdString().c_str());
		}

		if (process.waitForFinished()) {
			output = process.readAllStandardOutput().trimmed();
			error = process.readAllStandardError().trimmed();
		}
	}

	int code = process.exitCode();
	if (!error.isEmpty() || !success || code != 0)
	{
		throw std::runtime_error(
			QString("Code: %1\nError: %2")
				.arg(process.exitCode())
				.arg(error.isEmpty() ? "Unknown" : error)
				.toStdString());
	}

	return output;
}
开发者ID:SteveClement,项目名称:synergy,代码行数:36,代码来源:CoreInterface.cpp

示例8: create_with_binary

    /// Creates a new program with \p binary of \p binary_size in
    /// \p context.
    ///
    /// \see_opencl_ref{clCreateProgramWithBinary}
    static program create_with_binary(const unsigned char *binary,
                                      size_t binary_size,
                                      const context &context)
    {
        const cl_device_id device = context.get_device().id();

        cl_int error = 0;
        cl_int binary_status = 0;
        cl_program program_ = clCreateProgramWithBinary(context,
                                                        uint_(1),
                                                        &device,
                                                        &binary_size,
                                                        &binary,
                                                        &binary_status,
                                                        &error);
        if(!program_){
            BOOST_THROW_EXCEPTION(opencl_error(error));
        }
        if(binary_status != CL_SUCCESS){
            BOOST_THROW_EXCEPTION(opencl_error(binary_status));
        }

        return program(program_, false);
    }
开发者ID:2bbb,项目名称:compute,代码行数:28,代码来源:program.hpp

示例9: CompileShaders

GLuint CompileShaders(const GLchar** vertexShaderSource, const GLchar** fragmentShaderSource )
{
  //Compile vertex shader
  GLuint vertexShader( glCreateShader( GL_VERTEX_SHADER ) );
  glShaderSource( vertexShader, 1, vertexShaderSource, NULL );
  glCompileShader( vertexShader );
 
  //Compile fragment shader
  GLuint fragmentShader( glCreateShader( GL_FRAGMENT_SHADER ) );
  glShaderSource( fragmentShader, 1, fragmentShaderSource, NULL );
  glCompileShader( fragmentShader );
 
  //Link vertex and fragment shader together
  GLuint program( glCreateProgram() );
  glAttachShader( program, vertexShader );
  glAttachShader( program, fragmentShader );
  glLinkProgram( program );
 
  //Delete shaders objects
  glDeleteShader( vertexShader );
  glDeleteShader( fragmentShader );
 
  return program;
}
开发者ID:fsole,项目名称:GLSamples,代码行数:24,代码来源:MultidrawIndirect.cpp

示例10: program

ValueTree CtrlrPanel::getProgram(ValueTree treeToWriteTo)
{
	if (treeToWriteTo.isValid())
	{
		treeToWriteTo.removeAllChildren(0);
	}

	ValueTree program(Ids::panelState);
	program.setProperty (Ids::panelVersionMajor, getProperty(Ids::panelVersionMajor), 0);
	program.setProperty (Ids::panelVersionMinor, getProperty(Ids::panelVersionMinor), 0);
	program.setProperty (Ids::time, Time::getCurrentTime().currentTimeMillis(), 0);

	for (int i=0; i<ctrlrModulators.size(); i++)
	{
		CtrlrModulator *m = ctrlrModulators[i];

		ValueTree v(Ids::value);

		if ((bool)m->getProperty (Ids::modulatorIsStatic) == true)
			continue;

		v.setProperty(Ids::name, m->getName(),0);
		v.setProperty(Ids::value, m->getModulatorValue(),0);

		if (treeToWriteTo.isValid())
		{
			treeToWriteTo.addChild (v,-1,0);
		}
		else
		{
			program.addChild (v,-1,0);
		}
	}

	return (program);
}
开发者ID:noscript,项目名称:ctrlr,代码行数:36,代码来源:CtrlrPanel.cpp

示例11: main

int
main(void)
{
    bool ok = true;
    int buffer_storage[8];

    int_pair input_single;
    input_single.a = 1234567;

    int_pair input_pair;
    input_pair.a = -5588;
    input_pair.b = 8855;

    test_struct input;
    input.elementA = 1;
    input.elementB = 2;
    input.elementC = 3;
    input.elementD = 4;
    input.elementE = 5;
    input.elementF = 6;
    input.elementG = 7;
    input.elementH = 8;

    try {
        std::vector<cl::Platform> platformList;

        // Pick platform
        cl::Platform::get(&platformList);

        // Pick first platform
        cl_context_properties cprops[] = {
            CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(), 0};
        cl::Context context(CL_DEVICE_TYPE_ALL, cprops);

        // Query the set of devices attched to the context
        std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();

        // Create and program from source
        cl::Program::Sources sources({kernelSourceCode});
        cl::Program program(context, sources);

        // Build program
        program.build(devices);

        // Create buffer for that uses the host ptr C
        cl::Buffer cBuffer = cl::Buffer(
            context, 
            CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, 
            8 * sizeof(int), 
            (void *) &buffer_storage[0]);

        // Create command queue
        cl::CommandQueue queue(context, devices[0], 0);

        //
        // int_single
        //

        // Create kernel object
        cl::Kernel kernel_single(program, "test_single");

        // Set kernel args
        kernel_single.setArg(0, sizeof(int_single), &input_single);
        kernel_single.setArg(1, cBuffer);

        // Do the work
        queue.enqueueNDRangeKernel(
            kernel_single, 
            cl::NullRange, 
            cl::NDRange(1),
            cl::NullRange
        );

        // Map cBuffer to host pointer. This enforces a sync with 
        // the host backing space, remember we choose GPU device.
        int* output = (int*)queue.enqueueMapBuffer(
            cBuffer,
            CL_TRUE, // block 
            CL_MAP_READ,
            0,
            1 * sizeof(int));

        if (*output != 1234567) {
           std::cout 
               << "Small struct failure - size: 4 bytes expected: 123456 actual: "
               << *output << std::endl;
           ok = false;
        }

        queue.enqueueUnmapMemObject(cBuffer, output);

        //
        // int_pair
        //

        // Create kernel object
        cl::Kernel kernel_pair(program, "test_pair");

        // Set kernel args
        kernel_pair.setArg(0, sizeof(int_pair), &input_pair);
//.........这里部分代码省略.........
开发者ID:MoKarma,项目名称:pocl,代码行数:101,代码来源:test_structs_as_args.cpp

示例12: fprintf


//.........这里部分代码省略.........
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "Cisco HDLC";
	break;
      default:
        fprintf(stderr,"tcptrace did not understand link format (%d)!\n",type);
        fprintf(stderr,
		"\t If you can give us a capture file with this link format\n\
\t or even better, a patch to decipher this format, we shall add it in, \n\
\t in a future release.\n");
	rewind(stdin);
	return(NULL);
    }

    if (debug)
	fprintf(stderr,"Tcpdump format, physical type is %d (%s)\n",
		type, physname);

    /* set up some stuff */
    ip_buf = MallocZ(IP_MAXPACKET);


    return(pread_tcpdump);
}


/* support for writing a new pcap file */

void
PcapSavePacket(
    char *filename,
    struct ip *pip,
    void *plast)
{
    static MFILE *f_savefile = NULL;
    struct pcap_pkthdr phdr;
    int wlen;

    if (f_savefile == NULL) {
	struct pcap_file_header fhdr;

	/* try to open the file */
	if ((f_savefile = Mfopen(filename, "w")) == NULL) {
	    perror(filename);
	    exit(-1);
	}
	
	/* make up the header info it wants */
	/* this comes from version 2.4, no pcap routine handy :-(  */
	fhdr.magic = TCPDUMP_MAGIC;
	fhdr.version_major = PCAP_VERSION_MAJOR;
	fhdr.version_minor = PCAP_VERSION_MINOR;

	fhdr.thiszone = 0;	/* don't have this info, just make it up */
	fhdr.snaplen = 1000000;	/* don't have this info, just make it up */
	fhdr.linktype = PCAP_DLT_EN10MB; /* always Ethernet (10Mb) */
	fhdr.sigfigs = 0;

	/* write the header */
	Mfwrite((char *)&fhdr, sizeof(fhdr), 1, f_savefile);

	if (debug)
	    fprintf(stderr,"Created pcap save file '%s'\n", filename);
    }

    /* create the packet header */
    /* (copying time structure in 2 steps to avoid RedHat brain damage) */
    phdr.ts.tv_sec = current_time.tv_sec;
    phdr.ts.tv_usec = current_time.tv_usec;
    phdr.caplen = (char *)plast - (char *)pip + 1;
    phdr.caplen += EH_SIZE;	/* add in the ether header */
    phdr.len = EH_SIZE + ntohs(PIP_LEN(pip));	/* probably this */

    /* write the packet header */
    Mfwrite(&phdr, sizeof(phdr), 1, f_savefile);

    /* write a (bogus) ethernet header */
    memset(&eth_header,0,EH_SIZE);
    eth_header.ether_type = htons(ETHERTYPE_IP);
    Mfwrite(&eth_header, sizeof(eth_header), 1, f_savefile);

    /* write the IP/TCP parts */
    wlen = phdr.caplen - EH_SIZE;	/* remove the ether header */
    Mfwrite(pip, wlen, 1, f_savefile);
}
    


#else /* GROK_TCPDUMP */

void
PcapSavePacket(
    char *filename,
    struct ip *pip,
    void *plast)
{
    fprintf(stderr,"\
Sorry, packet writing only supported with the pcap library\n\
compiled into the program (See GROK_TCPDUMP)\n");
    exit(-2);
}
开发者ID:sgangam,项目名称:tcptraceALE,代码行数:101,代码来源:tcpdump.c

示例13: main

int main(int argc, char *argv[])
{
    SDL_Init(SDL_INIT_VIDEO);
    displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL);
    SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
    SDL_GL_MakeCurrent(displayWindow, context);
    
    glViewport(0, 0, 1280, 720);
    ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
    
    Matrix projectionMatrix;
    Matrix modelMatrix;
    Matrix viewMatrix;
    
    float lastFrameTicks = 0.0f;
    float elapsed = 0.0f;
    
    //Block
    float PositionY = -1.0f;
    float PositionX = -2.5f;
    
    float timer = 0.2f;
//    float num = -3.0f;
//    std::vector<float> points;
//    for (int i = 0; i < 12; i++) {
//        points[i] = num;
//        num += 0.5f;
//    }
    
//    int cord1 = rand() % 3 - 2;
//    int cord2 = rand() % 3;
//    int cord3 = rand() % 3 - 3;
//    int cord1 = points[rand()%12];
//    int cord2 = points[rand()%12];
//    int cord3 = points[rand()%12];
    
//    unsigned char levelData[1080][720];
    
    
    projectionMatrix.setOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f);
    
    glUseProgram(program.programID);
    
    
    
#ifdef _WINDOWS
    glewInit();
#endif
    
    SDL_Event event;
    bool done = false;
    while (!done) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
                done = true;
            }
        }
        
        float ticks = (float)SDL_GetTicks() / 1000.0f;
        elapsed = ticks - lastFrameTicks;
        lastFrameTicks = ticks;
        
        //Tile
        timer -= elapsed;
//        if (timer <= 0){
//            glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
//            glClear(GL_COLOR_BUFFER_BIT);
//            timer = 0.2f;
//        }
        
//        int cord1 = rand() % 3 - 2;
//        int cord2 = rand() % 3;
//        int cord3 = rand() % 3 - 3;
        
        glClearColor(0.4f, 0.2f, 0.4f, 1.0f);
        //glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        const Uint8 * keys = SDL_GetKeyboardState(NULL);
        if (keys[SDL_SCANCODE_UP] == 1){
            PositionY += elapsed * 3.1415926f / 2.0f;
            if (PositionY + 0.35f >= 2.0f) {
                PositionY -= elapsed * 3.1415926f / 2.0f;
            }
        }
        if (keys[SDL_SCANCODE_DOWN] == 1){
            PositionY -= elapsed * 3.1415926f / 2.0f;
            if (PositionY - 0.35f <= -2.0f) {
                PositionY += elapsed * 3.1415926f / 2.0f;
            }
        }
        if (keys[SDL_SCANCODE_RIGHT] == 1){
            PositionX += elapsed * 3.0f / 2.0f;
        }
        if (keys[SDL_SCANCODE_LEFT] == 1){
            PositionX -= elapsed * 3.0f / 2.0f;
        }
        
        
        glUseProgram(program.programID);
//.........这里部分代码省略.........
开发者ID:MarcNYU,项目名称:My_OpenGL_Games,代码行数:101,代码来源:main.cpp

示例14: program

void TransformEffect::dirty()
{
    // create pass
    if ( isDirty && currentRenderer()->getRenderTechnique() != Renderer::FIXED_PIPELINE ) 
    {
        EffectShaderProgram program(AUTO_LOGGER);
		if (boneMatricesBinder || (boneRotationsBinder && boneTranslationsBinder)) {
			program.addShader("Data/Shaders/skinned.vert");
		}
		else {
			program.addShader("Data/Shaders/rigid.vert");
		}
        program.addShader("Data/Shaders/fill.frag");
        program.addDefinition("#define DEPTH_ONLY");

        detail::Pass::DESC desc;
        desc.program = program.getProgram();

        detail::Pass::UNIFORM_DESC uniformDesc[4];
		{
			uniformDesc[0].uniformName = "worldViewProjMatrix";
			uniformDesc[0].parameter   = worldViewProjMatrixBinder.get();

			if (boneMatricesBinder) 
			{
				uniformDesc[1].uniformName = "boneMatrices";
				uniformDesc[1].parameter   = boneMatricesBinder.get();
			}

            if (boneRotationsBinder)
            {
				uniformDesc[2].uniformName = "boneRotations";
				uniformDesc[2].parameter   = boneRotationsBinder.get();
            }

            if (boneTranslationsBinder)
            {
				uniformDesc[3].uniformName = "boneTranslations";
				uniformDesc[3].parameter   = boneTranslationsBinder.get();
            }

			desc.uniforms    = uniformDesc;
			desc.numUniforms = 4;
		}
        
        sgl::DepthStencilState::DESC dsDesc;
        {
            dsDesc.depthEnable    = true;
            dsDesc.depthFunc      = sgl::DepthStencilState::LEQUAL;
            dsDesc.stencilEnable  = false;
            dsDesc.depthWriteMask = true;
        }
        desc.depthStencilState = currentDevice()->CreateDepthStencilState(dsDesc);
        
        sgl::RasterizerState::DESC rastDesc;
        {
            rastDesc.cullMode  = sgl::RasterizerState::BACK;
            rastDesc.fillMode  = sgl::RasterizerState::SOLID;
            rastDesc.colorMask = 0;
        }
        desc.rasterizerState = currentDevice()->CreateRasterizerState(rastDesc);

        depthPass.reset( new detail::Pass(desc) );

        // create back faces pass
        {
            rastDesc.cullMode  = sgl::RasterizerState::FRONT;
            rastDesc.fillMode  = sgl::RasterizerState::SOLID;
            rastDesc.colorMask = 0;
        }
        desc.rasterizerState = currentDevice()->CreateRasterizerState(rastDesc);
        
        backFaceDepthPass.reset( new detail::Pass(desc) );
		
        isDirty = false;
    }
}
开发者ID:BackupTheBerlios,项目名称:slon,代码行数:77,代码来源:TransformEffect.cpp

示例15: main

int main(int argc, char *argv[])
{
    float *h_psum;					// vector to hold partial sum
    int in_nsteps = INSTEPS;		// default number of steps (updated later to device prefereable)
    int niters = ITERS;				// number of iterations
    int nsteps;
    float step_size;
    ::size_t nwork_groups;
    ::size_t max_size, work_group_size = 8;
    float pi_res;

    cl::Buffer d_partial_sums;

    try
    {
        cl_uint deviceIndex = 0;
        parseArguments(argc, argv, &deviceIndex);

        // Get list of devices
        std::vector<cl::Device> devices;
        unsigned numDevices = getDeviceList(devices);

        // Check device index in range
        if (deviceIndex >= numDevices)
        {
          std::cout << "Invalid device index (try '--list')\n";
          return EXIT_FAILURE;
        }

        cl::Device device = devices[deviceIndex];

        std::string name;
        getDeviceName(device, name);
        std::cout << "\nUsing OpenCL device: " << name << "\n";

        std::vector<cl::Device> chosen_device;
        chosen_device.push_back(device);
        cl::Context context(chosen_device);
        cl::CommandQueue queue(context, device);

        // Create the program object
        cl::Program program(context, util::loadProgram("../pi_ocl.cl"), true);

        // Create the kernel object for quering information
        cl::Kernel ko_pi(program, "pi");

        // Get the work group size
        work_group_size = ko_pi.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
        //printf("wgroup_size = %lu\n", work_group_size);

        cl::make_kernel<int, float, cl::LocalSpaceArg, cl::Buffer> pi(program, "pi");

        // Now that we know the size of the work_groups, we can set the number of work
        // groups, the actual number of steps, and the step size
        nwork_groups = in_nsteps/(work_group_size*niters);

        if ( nwork_groups < 1) {
            nwork_groups = device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
            work_group_size=in_nsteps / (nwork_groups*niters);
        }

        nsteps = work_group_size * niters * nwork_groups;
        step_size = 1.0f/static_cast<float>(nsteps);
        std::vector<float> h_psum(nwork_groups);

        printf(
            " %d work groups of size %d.  %d Integration steps\n",
            (int)nwork_groups,
            (int)work_group_size,
            nsteps);

        d_partial_sums = cl::Buffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * nwork_groups);

        util::Timer timer;

        // Execute the kernel over the entire range of our 1d input data set
        // using the maximum number of work group items for this device
        pi(
            cl::EnqueueArgs(
                    queue,
                    cl::NDRange(nsteps / niters),
                    cl::NDRange(work_group_size)),
                    niters,
                    step_size,
                    cl::Local(sizeof(float) * work_group_size),
                    d_partial_sums);

        cl::copy(queue, d_partial_sums, h_psum.begin(), h_psum.end());

        // complete the sum and compute final integral value
        pi_res = 0.0f;
        for (unsigned int i = 0; i< nwork_groups; i++) {
                pi_res += h_psum[i];
        }
        pi_res = pi_res * step_size;

        //rtime = wtime() - rtime;
        double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.;
        printf("\nThe calculation ran in %lf seconds\n", rtime);
        printf(" pi = %f for %d steps\n", pi_res, nsteps);
//.........这里部分代码省略.........
开发者ID:BenElgar,项目名称:Exercises-Solutions,代码行数:101,代码来源:pi_ocl.cpp


注:本文中的program函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。