Skip to content

Instantly share code, notes, and snippets.

@sergev
Created July 3, 2019 23:30
Show Gist options
  • Save sergev/53be5ce386595adb1e0e7da5da48f2b3 to your computer and use it in GitHub Desktop.
Save sergev/53be5ce386595adb1e0e7da5da48f2b3 to your computer and use it in GitHub Desktop.
Compare libyaml and libyaml-cpp parsers for speed
//
// 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;
}
@sergev
Copy link
Author

sergev commented Jul 3, 2019

Typically C library is from 8 to 10 times faster.
For example:

$ ./run conv_example.yaml 
Load file "conv_example.yaml"
C elapsed time: 0.474 seconds
C++ elapsed time: 3.923 seconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment