Advertisement

今天闲来无事测了一下cout.put和putchar的速度。

阅读量:

环境——编译器:MSVC;标准:C++14;模式:Release
测试代码:

今天闲来无事测了一下cout.put和putchar的速度。

环境——编译器:MSVC;标准:C++14;模式:Release
测试代码:

复制代码
 #include <iostream>

    
 #include <chrono>
    
 using namespace std;
    
  
    
 constexpr size_t times1 = 2'0000ULL;
    
 constexpr size_t times2 = 10'0000ULL;
    
  
    
 int main()
    
 {
    
 	ios::sync_with_stdio(false);
    
 	cout.tie(nullptr);
    
 	cin.tie(nullptr);
    
  
    
 	// 第一次测试
    
 	const auto first_test_begin = chrono::system_clock::now();
    
  
    
 	for (size_t i = 0; i < times1; ++i)
    
 		cout.put('A');
    
  
    
 	const auto first_test_end = chrono::system_clock::now();
    
  
    
 	// 第二次测试
    
 	const auto second_test_begin = chrono::system_clock::now();
    
  
    
 	for (size_t i = 0; i < times1; ++i)
    
 		putchar('B');
    
  
    
 	const auto second_test_end = chrono::system_clock::now();
    
  
    
 	// 第三次测试
    
 	const auto third_test_begin = chrono::system_clock::now();
    
  
    
 	for (size_t i = 0; i < times2; ++i)
    
 		cout.put('C');
    
  
    
 	const auto third_test_end = chrono::system_clock::now();
    
  
    
 	// 第四次测试
    
 	const auto fourth_test_begin = chrono::system_clock::now();
    
  
    
 	for (size_t i = 0; i < times2; ++i)
    
 		putchar('D');
    
  
    
 	const auto fourth_test_end = chrono::system_clock::now();
    
  
    
 	// 输出结果
    
 	cout << "Test1: " << (first_test_end - first_test_begin).count() << '\n';
    
 	cout << "Test2: " << (second_test_end - second_test_begin).count() << '\n';
    
 	cout << "Test3: " << (third_test_end - third_test_begin).count() << '\n';
    
 	cout << "Test4: " << (fourth_test_end - fourth_test_begin).count() << '\n';
    
  
    
 	return 0;
    
 }

输出:

......一堆字符
Test1: 19128735
Test2: 19834277
Test3: 35565828
Test4: 34590586

Summary: 对于小于 2, 点后的数据量(即 1999 点以下)使用 std::cout::put() 的效率更高(在实现 ios::sync_with_stdio(false) 和 tie 优化后);而对于大于 1999 点的数据量 std::putchar 的效率更高

呵呵,这会ostream终于不是啥也不是了。

全部评论 (0)

还没有任何评论哟~