Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Compare libyaml and libyaml-cpp parsers for speed.
- //
- // Compile with:
- // g++ -O run.cpp -lyaml-cpp -lyaml -o run
- //
- #include <stdio.h>
- #include <stdlib.h>
- #include <getopt.h>
- #include <stdint.h>
- #include <sys/time.h>
- #include <yaml.h>
- #include <yaml-cpp/yaml.h>
- //
- // Load YAML file using C library.
- //
- void load_yaml_c(const char *filename)
- {
- struct timeval t0, t1;
- gettimeofday(&t0, 0);
- // Initialize parser.
- yaml_parser_t parser;
- if (!yaml_parser_initialize(&parser)) {
- printf("%s: Failed to initialize YAML parser!\n", filename);
- exit(-1);
- }
- // Set input file.
- FILE *fh = fopen(filename, "r");
- if (! fh) {
- perror(filename);
- exit(-1);
- }
- yaml_parser_set_input_file(&parser, fh);
- // Parse the document.
- yaml_document_t yaml_document;
- if (!yaml_parser_load(&parser, &yaml_document)) {
- fclose(fh);
- printf("%s: YAML parser error %d\n", filename, parser.error);
- exit(-1);
- }
- fclose(fh);
- yaml_parser_delete(&parser);
- // Find root element.
- if (!yaml_document_get_root_node(&yaml_document)) {
- printf("%s: YAML file is empty\n", filename);
- yaml_document_delete(&yaml_document);
- exit(-1);
- }
- // Delete loaded data.
- yaml_document_delete(&yaml_document);
- gettimeofday(&t1, 0);
- uintmax_t usec = (t1.tv_usec - t0.tv_usec) +
- (t1.tv_sec - t0.tv_sec) * 1000000UL;
- printf("C elapsed time: %.3f seconds\n", usec / 1000000.0);
- }
- //
- // Load YAML file using C++ library.
- //
- void load_yaml_cxx(const char *filename)
- {
- struct timeval t0, t1;
- gettimeofday(&t0, 0);
- std::vector<YAML::Node> root = YAML::LoadAllFromFile(filename);
- // Delete loaded data.
- root.clear();
- gettimeofday(&t1, 0);
- uintmax_t usec = (t1.tv_usec - t0.tv_usec) +
- (t1.tv_sec - t0.tv_sec) * 1000000UL;
- printf("C++ elapsed time: %.3f seconds\n", usec / 1000000.0);
- }
- void usage()
- {
- printf("Test YAML input\n");
- printf("Usage:\n");
- printf(" run input.yml\n");
- exit(-1);
- }
- int main(int argc, char **argv)
- {
- for (;;) {
- switch (getopt(argc, argv, "")) {
- case EOF:
- break;
- default:
- usage();
- }
- break;
- }
- argc -= optind;
- argv += optind;
- if (argc != 1)
- usage();
- const char *filename = argv[0];
- printf("Load file \"%s\"\n", filename);
- load_yaml_c(filename);
- load_yaml_cxx(filename);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement