abench.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/NumericLimits.h>
  7. #include <AK/Types.h>
  8. #include <LibCore/ArgsParser.h>
  9. #include <LibCore/ElapsedTimer.h>
  10. #include <LibFileSystem/FileSystem.h>
  11. #include <LibMain/Main.h>
  12. #include <LibMedia/Audio/Loader.h>
  13. #include <stdio.h>
  14. // The Kernel has problems with large anonymous buffers, so let's limit sample reads ourselves.
  15. static constexpr size_t MAX_CHUNK_SIZE = 1 * MiB / 2;
  16. ErrorOr<int> serenity_main(Main::Arguments args)
  17. {
  18. StringView path {};
  19. int sample_count = -1;
  20. Core::ArgsParser args_parser;
  21. args_parser.set_general_help("Benchmark audio loading");
  22. args_parser.add_positional_argument(path, "Path to audio file", "path");
  23. args_parser.add_option(sample_count, "How many samples to load at maximum", "sample-count", 's', "samples");
  24. args_parser.parse(args);
  25. auto maybe_loader = Audio::Loader::create(path);
  26. if (maybe_loader.is_error()) {
  27. warnln("Failed to load audio file: {}", maybe_loader.error());
  28. return 1;
  29. }
  30. auto loader = maybe_loader.release_value();
  31. Core::ElapsedTimer sample_timer { Core::TimerType::Precise };
  32. i64 total_loader_time = 0;
  33. int remaining_samples = sample_count > 0 ? sample_count : NumericLimits<int>::max();
  34. unsigned total_loaded_samples = 0;
  35. for (;;) {
  36. if (remaining_samples > 0) {
  37. sample_timer = sample_timer.start_new();
  38. auto samples = loader->get_more_samples(min(MAX_CHUNK_SIZE, remaining_samples));
  39. total_loader_time += sample_timer.elapsed_milliseconds();
  40. if (!samples.is_error()) {
  41. remaining_samples -= samples.value().size();
  42. total_loaded_samples += samples.value().size();
  43. if (samples.value().size() == 0)
  44. break;
  45. } else {
  46. warnln("Error while loading audio: {}", samples.error());
  47. return 1;
  48. }
  49. } else
  50. break;
  51. }
  52. auto time_per_sample = static_cast<double>(total_loader_time) / static_cast<double>(total_loaded_samples) * 1000.;
  53. auto playback_time_per_sample = (1. / static_cast<double>(loader->sample_rate())) * 1000'000.;
  54. outln("Loaded {:10d} samples in {:06.3f} s, {:9.3f} µs/sample, {:6.1f}% speed (realtime {:9.3f} µs/sample)", total_loaded_samples, static_cast<double>(total_loader_time) / 1000., time_per_sample, playback_time_per_sample / time_per_sample * 100., playback_time_per_sample);
  55. return 0;
  56. }