#include <iostream>
#include <vector>
#include <chrono>
#include <utility>
using CLOCK = std::chrono::high_resolution_clock;
// Function that takes ownership via perfect forwarding
template<typename T>
void process_with_forward(T&& data) {
// Use the vector directly (could also move if needed)
std::vector<int> v = std::forward<T>(data);
// Do some dummy computation to prevent compiler from optimizing away
volatile size_t sink = v.size();
(void)sink;
}
// Function that always makes a copy
template<typename T>
void process_with_copy(T data) {
std::vector<int> v = data;
volatile size_t sink = v.size();
(void)sink;
}
int main() {
constexpr size_t NUM_TESTS = 10000;
constexpr size_t VECTOR_SIZE = 100000;
// Benchmark perfect forwarding version
auto start_forward = CLOCK::now();
for (size_t i = 0; i < NUM_TESTS; ++i) {
process_with_forward(std::vector<int>(VECTOR_SIZE)); // pass rvalue
}
auto end_forward = CLOCK::now();
// Benchmark copying version
auto start_copy = CLOCK::now();
for (size_t i = 0; i < NUM_TESTS; ++i) {
process_with_copy(std::vector<int>(VECTOR_SIZE)); // pass rvalue
}
auto end_copy = CLOCK::now();
// Output results
auto microseconds_forward = std::chrono::duration_cast<std::chrono::milliseconds>(end_forward - start_forward).count();
auto microseconds_copy = std::chrono::duration_cast<std::chrono::milliseconds>(end_copy - start_copy).count();
std::cout << "With perfect forwarding: " << microseconds_forward << " ms\n";
std::cout << "With unnecessary copy: " << microseconds_copy << " ms\n";
return 0;
}