zoukankan      html  css  js  c++  java
  • c++ 常用的函数

    1,计算变量大小

    _msize  #计算new出来的内存大小,单位是字节

    sizeof    #计算数据类型大小,比如int是4字节,mat是96字节,vector不管多大都是32字节

    strlen    #数组中由多少个元素

    2,printf的格式化字符串参数

    打印double:%f

    打印long:ubuntu是这样的:%ld(因为在ubuntu中,long有8个字节)

     3,时间相关

    windows上可用,据说此方法是cpu计时,也不甚准确,

    #include <time.h>
    #include <windows.h> //时间的头文件 clock_t start,ends; //clock_t实际上就是一个long start=clock(); //从开启这个程序进程 到 程序中调用clock()函数时 之间的毫秒数 Sleep(50); ends=clock(); cout<<ends-start<<endl; //此函数常用于计算时间差

    可以尝试这个

    Windows: 
    QueryPerformanceCounter 
    QueryPerformanceFrequency

    ubuntu上不建议使用clock,据说计时不准,可以参考如下代码:

    #include <sys/time.h>
    #include <stdio.h>
    #include <unistd.h>
    using namespace std;
    //如下好像是sys/time.h内置的时间结构
    //struct timeval{
    //      long tv_sec;
    //      long tv_usec;
    //};
    //struct timezone{
    //      int tz_minutesweat;
    //      int tz_dsttime;
    //};
    
    int main(){
      struct timeval t1,t2;
      gettimeofday(&t1,NULL);
      int suma;
      for(int a=0;a<10000;a++){
          suma=suma+a;
      };
      sleep(10);
      gettimeofday(&t2,NULL);
      double timegap=(t2.tv_sec-t1.tv_sec)*1000+(t2.tv_usec-t1.tv_usec)*1.0/1000;
       //记得乘以1.0不然没有小数后的几位
      printf("tv1:%ld,%ld
    ",t1.tv_sec,t1.tv_usec);
      printf("tv2:%ld,%ld
    ",t2.tv_sec,t2.tv_usec);
      printf("timegap:%f
    ",timegap);
    }

    编译命令:

    gcc timetest.cpp -o out -std=c++11 -lstdc++

     4,fstream读取或者写出文件流

    原作者写得灰常好,望尘莫及,直接跳转吧。链接

    #include <iostream>
    #include <fstream>
    using namespace std;
    int main() {
        char filepath[255];
        sprintf_s(filepath,"%s","D:\ctest\Project1\x64\Release\1.log");
        std::ifstream t(filepath, std::ios::binary);
        //std::ios::binary以二进制方式打开,主要和
    换行符有关系
        t.seekg(0, ios::end);
        int loglength = t.tellg();//单位是字节数,注意,返回的长度将
    也计算在内
        printf("stream length: %d
    ",loglength);
        return 0;
    }
    //以上是求log文件中有多少字节数据的方法,ps:vs2015
  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    win10右键新建markdown文件
    force down pool_member
    自控力差,你可能忽略了一种更底层的能力
    多线程的通信问题
    多线程的安全问题
    Java实现多线程的两种方式
    为什么你成不了数据分析高手?可能是缺少这个思维
    jstack && jmap
    对ElasticSearch主副分片的理解
  • 原文地址:https://www.cnblogs.com/0-lingdu/p/12407762.html
Copyright © 2011-2022 走看看