utf8tows Windows vs2019 c++ 17 有一个意想不到的锁可能影响性能,用的时候,千万小心

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <thread>
#include <atlstr.h>
#include <atlconv.h>
#include <cassert>
#include <codecvt>
std::wstring utf82ws(const char* str)
{
	auto& err = get_error_string();

	std::wstring_convert<std::codecvt_utf8<wchar_t>> conv(err.err, err.werr);
	return conv.from_bytes(str);
}
//assert(wcscmp(CA2W(strUtf8.c_str(), CP_UTF8).m_psz, strWs.c_str()) == 0);
void f()
{
	std::string strUtf8 = "hello,world";
	std::wstring strWs = L"hello,world";
	int i = 0;
	while (1) {
		assert(utf82ws(strUtf8.c_str()) == strWs);
		if (++i == 1000) {
			i = 0;
		}
	}
}
int main() {
	std::thread t1(f);
	std::thread t2(f);

	t1.join();
	t2.join();

	return 1;
}

cpu 运行结果如下:

预期两个while 死循环,cpu 占用应该是25%,wpa 分析一下:

按照等待时间排序,排查一下是否有锁操作

左边是cpu 执行的比率,显然,对于那种不干活的,我们不关心,因此,分析10584和25392线程即可:

具体这么设计的原因是啥,不可知。

 

测试微软的WideCharToMultiByte函数:,ca2w 内部实现就是这个:


#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <thread>
#include <atlstr.h>
#include <atlconv.h>
#include <cassert>
#include <codecvt>
std::wstring utf82ws(const char* str)
{
	auto& err = get_error_string();

	std::wstring_convert<std::codecvt_utf8<wchar_t>> conv(err.err, err.werr);
	return conv.from_bytes(str);
}

void f()
{
	std::string strUtf8 = "hello,world";
	std::wstring strWs = L"hello,world";
	int i = 0;
	while (1) {
		//assert(utf82ws(strUtf8.c_str()) == strWs);
		assert(wcscmp(CA2W(strUtf8.c_str(), CP_UTF8).m_psz, strWs.c_str()) == 0);
		if (++i == 1000) {
			i = 0;
		}
	}
}
int main() {
	std::thread t1(f);
	std::thread t2(f);

	t1.join();
	t2.join();

	return 1;
}

看到了我们的理想,25%

这种莫名其妙的锁,简直就是性能杀手,官方文档暂时没有找到介绍这里的锁的东西,暂时不管了,这个函数还是少用

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值