c++ 常用的函数

1,计算变量大小

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

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

strlen    #数组中由多少个元素

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

打印double:%f

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

 3,时间相关

windows上可用:

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

 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\n",t1.tv_sec,t1.tv_usec);
  printf("tv2:%ld,%ld\n",t2.tv_sec,t2.tv_usec);
  printf("timegap:%f\n",timegap);
}

编译命令:

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

猜你喜欢

转载自www.cnblogs.com/0-lingdu/p/12407762.html
今日推荐