C++函数中的静态变量
程序员文章站
2022-06-03 22:24:55
...
在C++中,可以在成员函数中使用静态变量,从而间接达到在hpp中定义属于某个类的静态变量的目的(无需再在cpp文件中初始化)
然而,这中方案在速度上会有一定的损耗。
1、该变量首次使用时才进行初始化
When do function-level static variables get allocated/initialized?:https://*.com/questions/55510/when-do-function-level-static-variables-get-allocated-initialized
2、每次使用都多出一个if语句及atomic操作(为了多线程安全性)
Does a function local static variable automatically incur a branch?https://*.com/questions/23829389/does-a-function-local-static-variable-automatically-incur-a-branch
速度对比:
单线程调用1亿次,慢14ms左右
然而,这中方案在速度上会有一定的损耗。
1、该变量首次使用时才进行初始化
When do function-level static variables get allocated/initialized?:https://*.com/questions/55510/when-do-function-level-static-variables-get-allocated-initialized
2、每次使用都多出一个if语句及atomic操作(为了多线程安全性)
Does a function local static variable automatically incur a branch?https://*.com/questions/23829389/does-a-function-local-static-variable-automatically-incur-a-branch
速度对比:
单线程调用1亿次,慢14ms左右
- static var use: 43ms
- static method var use: 67ms
class TestStatic{ public: static std::vector<int> v; inline static std::vector<int>& mv(){ static std::vector<int> v; return v; } }; std::vector<int> TestStatic::v; void testStatic(){ int n=10000000; int r=0; int r2=0; TestStatic::v.push_back(0); TestStatic::mv().push_back(0); LC::TimerAccurate timer; for (int i=0;i<n;++i){ r+=TestStatic::v.size(); // TestStatic::v[0]++; } std::cout<<"static var use: \t"<<timer.getElapsedTime_in_ms()<<"ms"<<std::endl; timer.restart(); for (int i=0;i<n;++i){ r2+=TestStatic::mv().size(); // TestStatic::mv()[0]++; } std::cout<<"static method var use: \t"<<timer.getElapsedTime_in_ms()<<"ms"<<std::endl; timer.restart(); std::cout<<r<<std::endl; std::cout<<r2<<std::endl; std::cout << "End of test, " << __FUNCTION__ << std::endl; exit(0); }
上一篇: 汇顶:今年量产LCD屏下光学指纹
推荐阅读
-
Python函数中*args和**kwargs来传递变长参数的用法
-
介绍几个php4中非常有用的数组函数转载关联数组等同于PERL里的哈希数组。以前我一直以为PHP里没...
-
PHP SPL标准库中的常用函数介绍_PHP教程
-
solaris 11中怎么在没有安装mysql的机器下使用mysql_connect等函数
-
LServer中的几个重要时间函数
-
php中可能用来加密字符串的函数[base64_encode、urlencode、sha1]_PHP教程
-
PHP中可以自动分割查询字符的Parse_str函数使用示例,parse_str示例_PHP教程
-
详细解读MySQL中COUNT函数的用法_MySQL
-
PHP中全局变量$GLOBALS和global的区别
-
SQLSERVER数据库中的 时间函数