Created
December 4, 2025 09:49
-
-
Save datsuns/0793516feb606fee35a65d018e554ffd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include "NvInfer.h" | |
| #include "NvOnnxParser.h" | |
| #include <fstream> | |
| #include <iostream> | |
| using namespace nvinfer1; | |
| // ロガー | |
| class Logger : public ILogger { | |
| public: | |
| void log(Severity severity, const char* msg) noexcept override { | |
| if (severity <= Severity::kINFO) | |
| std::cout << msg << std::endl; | |
| } | |
| } gLogger; | |
| int main() | |
| { | |
| IBuilder* builder = createInferBuilder(gLogger); | |
| // explicitBatch | |
| const auto explicitBatch = | |
| 1U << static_cast<uint32_t>(NetworkDefinitionCreationFlag::kEXPLICIT_BATCH); | |
| INetworkDefinition* network = builder->createNetworkV2(explicitBatch); | |
| // ONNX パーサ | |
| auto parser = nvonnxparser::createParser(*network, gLogger); | |
| if (!parser->parseFromFile("my.onnx", static_cast<int>(ILogger::Severity::kWARNING))) { | |
| std::cerr << "ERROR: Failed to parse ONNX file" << std::endl; | |
| return -1; | |
| } | |
| // BuilderConfig | |
| IBuilderConfig* config = builder->createBuilderConfig(); | |
| // FP16 有効化 | |
| if (builder->platformHasFastFp16()) { | |
| config->setFlag(BuilderFlag::kFP16); | |
| } | |
| // ★ trtexec と同じ Workspace サイズ(16 MiB)を設定 | |
| const size_t workspaceSize = 1ULL << 24; // 16 MiB | |
| config->setMemoryPoolLimit( | |
| MemoryPoolType::kWORKSPACE, | |
| workspaceSize | |
| ); | |
| // エンジン生成 | |
| ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config); | |
| if (!engine) { | |
| std::cerr << "ERROR: Engine build failed!" << std::endl; | |
| return -1; | |
| } | |
| // 序列化して保存 | |
| IHostMemory* serializedEngine = engine->serialize(); | |
| std::ofstream ofs("output.trt", std::ios::binary); | |
| ofs.write((char*)serializedEngine->data(), serializedEngine->size()); | |
| ofs.close(); | |
| // 後処理 | |
| serializedEngine->destroy(); | |
| engine->destroy(); | |
| parser->destroy(); | |
| network->destroy(); | |
| config->destroy(); | |
| builder->destroy(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment